class FormGenerator {
    constructor(options) {
        const { container, initialData, fieldCategories, expandedCategories = {} } = options;
        // 处理容器参数，可以是选择器字符串或DOM元素
        this.container = typeof container === 'string'
            ? document.querySelector(container)
            : container;
        this.originalData = JSON.parse(JSON.stringify(initialData)); // 深拷贝原始数据
        this.data = JSON.parse(JSON.stringify(initialData)); // 用于修改的数据
        this.categories = fieldCategories;
        this.expandedCategories = expandedCategories; // 新增：存储展开状态
        // 初始化图片预览容器
        this.imagePreviews = new Map();
        // 添加关联字段映射
        this.linkedFields = {
            '软件配置V1.蓝牙名': '软件配置V1.音频名',
            '软件配置V1.音频名': '软件配置V1.蓝牙名',
            // 添加语言字段的关联
            '软件配置V2.语言.支持语言': '软件配置V2.语言.默认语言'
        };
        this.inputElements = new Map(); // 存储字段与输入元素的映射
        
        // 添加图库数据更新监听器
        this.setupGalleryUpdateListener();
    }




    // 获取对象的嵌套属性值
    getNestedValue(obj, path) {
        if (!path || !obj) return undefined;
        const keys = path.split('.');
        return keys.reduce((prev, current) => {
            // 处理可能的嵌套对象
            if (prev && typeof prev === 'object' && current in prev) {
                return prev[current];
            }
            return '';
        }, obj);
    }

    // 设置对象的嵌套属性值
    setNestedValue(obj, path, value) {
        console.log('设置嵌套值:', path, '值:', value);
        const parts = path.split('.');
        const lastPart = parts.pop();
        const nestedObj = parts.reduce((acc, part) => {
            if (!acc[part]) acc[part] = {};
            return acc[part];
        }, obj);
        nestedObj[lastPart] = value;
        console.log('设置完成，验证数据:', this.getNestedValue(obj, path));
    }

    // 更新关联字段的值
    updateLinkedFieldInput(fieldPath, value) {
        const inputEl = this.inputElements.get(fieldPath);
        if (inputEl && inputEl.type === 'hidden') {
            inputEl.value = value;
            // 找到对应的checkbox并更新状态
            const toggleSwitch = inputEl.parentElement.querySelector('.toggle-switch input[type="checkbox"]');
            if (toggleSwitch) {
                toggleSwitch.checked = value === 'on';
            }
        } else if (inputEl && inputEl.tagName === 'INPUT' && inputEl.type === 'text') {
            // 处理文本输入框的情况
            const originalOnInput = inputEl.oninput;
            inputEl.oninput = null;
            inputEl.value = value;
            inputEl.oninput = originalOnInput;
        }else if (inputEl && inputEl.tagName === 'SELECT') {
            // 处理下拉选择框的情况
            const originalOnChange = inputEl.onchange;
            inputEl.onchange = null;
            inputEl.value = value;
            inputEl.onchange = originalOnChange;
        }
    }

    // 设置图库数据更新监听器
    setupGalleryUpdateListener() {
        document.addEventListener('galleryDataUpdated', (event) => {
            const { fieldName, newGalleryData, screenShape } = event.detail;
            console.log(`接收到图库更新事件: ${fieldName}, 屏幕形状: ${screenShape}`);
            
            // 更新全局变量，确保下次打开图库时使用最新数据
            if (fieldName === '参考附图') {
                window.pictureMainMenuStyleGallery = newGalleryData;
                console.log('已更新全局图库数据:', window.pictureMainMenuStyleGallery);
            }
        });
    }

    renderForm() {
        this.container.innerHTML = '';
        this.imagePreviews.clear();
        this.inputElements.clear();

        Object.keys(this.categories).forEach(categoryName => {
            const categoryFields = this.categories[categoryName];
            const categorySection = document.createElement('div');
            categorySection.className = 'category-section';
            categorySection.dataset.category = categoryName;

            // 检查是否应该展开
            const isExpanded = this.expandedCategories[categoryName] !== false; // 默认展开

            const titleEl = document.createElement('h2');
            titleEl.className = 'category-title';
            titleEl.textContent = categoryName;
            titleEl.style.cursor = 'pointer'; // 显示为可点击

            // 添加展开/折叠图标
            const toggleIcon = document.createElement('span');
            toggleIcon.className = 'toggle-icon' + (isExpanded ? ' expanded' : '');
            toggleIcon.textContent = isExpanded ? '−' : '+';
            // 将图标从右侧移到左侧
            toggleIcon.style.float = 'right';
            toggleIcon.style.marginLeft = '10px';
            toggleIcon.style.float = 'left';
            toggleIcon.style.marginRight = '10px';
            titleEl.appendChild(toggleIcon);

            // 创建类别内容容器
            const categoryContent = document.createElement('div');
            categoryContent.className = 'category-content';
            categoryContent.style.display = isExpanded ? 'block' : 'none';

            // 添加点击事件
            titleEl.addEventListener('click', () => {
                const isCurrentlyExpanded = categoryContent.style.display === 'block';
                categoryContent.style.display = isCurrentlyExpanded ? 'none' : 'block';
                toggleIcon.textContent = isCurrentlyExpanded ? '+' : '−';
                toggleIcon.classList.toggle('expanded', !isCurrentlyExpanded); // 更新样式类
                this.expandedCategories[categoryName] = !isCurrentlyExpanded;

            });

            categorySection.appendChild(titleEl);
            categorySection.appendChild(categoryContent);

            categoryFields.forEach(field => {
                // 为软件配置V3添加动态字段配置
                // 为软件配置V3添加动态字段配置
                if (field.field === '软件配置V3') {
                    //field.input_type = 'object';
                    field.array_mode = true;

                    // 从原始fieldCategories中获取object_fields定义
                    const originalObjectFields = field.object_fields || [];

                    field.object_fields = [
                        {
                            field: '分辨率',
                            label: '分辨率',
                            input_type: 'select',
                            options: originalObjectFields.find(f => f.field === '分辨率')?.options || [],
                            linked_fields: originalObjectFields.find(f => f.field === '分辨率')?.linked_fields || []
                        },
                        {
                            field: '屏',
                            label: '屏',
                            input_type: 'select',
                            options: originalObjectFields.find(f => f.field === '屏')?.options || []
                        },
                        {
                            field: 'TP',
                            label: 'TP',
                            input_type: 'select',
                            options: originalObjectFields.find(f => f.field === 'TP')?.options || []
                        }
                    ];
                }
                const formGroup = document.createElement('div');
                formGroup.className = 'form-group';

                const labelEl = document.createElement('label');
                labelEl.textContent = field.label;
                formGroup.appendChild(labelEl);

                // 优先使用field_path，否则使用field.field
                const dataPath = field.field_path || field.field;
                const currentValue = this.getNestedValue(this.data, dataPath);
                let inputEl;

                switch (field.input_type) {
                    case 'text':
                        inputEl = document.createElement('input');
                        inputEl.type = 'text';
                        inputEl.value = currentValue;
                        // 存储输入元素引用
                        this.inputElements.set(field.field, inputEl);

                        // 添加输入事件监听器
                        inputEl.addEventListener('input', (e) => {
                            const value = e.target.value;
                            this.setNestedValue(this.data, dataPath, value);

                            // 检查是否有关联字段需要同步更新
                            if (this.linkedFields[dataPath]) {
                                const linkedFieldPath = this.linkedFields[dataPath];
                                this.setNestedValue(this.data, linkedFieldPath, value);
                                this.updateLinkedFieldInput(linkedFieldPath, value);
                            }
                        });
                        break;

                    case 'textarea':
                        inputEl = document.createElement('textarea');
                        inputEl.rows = 3;
                        inputEl.value = currentValue;
                        inputEl.addEventListener('input', (e) => {
                            this.setNestedValue(this.data, dataPath, e.target.value);
                        });
                        break;

                    case 'select':
                        inputEl = document.createElement('select');
                        if (field.options && field.options.length) {
                            field.options.forEach(option => {
                                const optionEl = document.createElement('option');
                                optionEl.value = option;
                                optionEl.textContent = option;
                                optionEl.selected = currentValue === option;
                                inputEl.appendChild(optionEl);
                            });
                        }
                        inputEl.addEventListener('change', async (e) => {


                            const selectedValue = e.target.value;
                            this.setNestedValue(this.data, dataPath, selectedValue);

                            // 检查是否有linked_fields配置
                            if (field.linked_fields && field.linked_fields.length > 0) {
                                // 特殊处理分辨率字段
                                if (field.field === '分辨率') {
                                    // 调用getAssemblyByResolution函数获取数据
                                    try {
                                        const assemblyData = await getAssemblyByResolution(selectedValue);

                                        // 更新屏字段
                                        if (assemblyData.screenArray && assemblyData.screenArray.length > 0) {
                                            const screenValue = assemblyData.screenArray[0].screen;
                                            this.setNestedValue(this.data, '屏', screenValue);
                                            // 更新对应的DOM元素
                                            const screenSelect = this.container.querySelector(`select[data-field="屏"]`);
                                            if (screenSelect) {
                                                // 获取当前默认值（如果有）
                                                const currentScreenValue = this.getNestedValue(this.data, '屏') || '';
                                                
                                                // 清空现有选项
                                                screenSelect.innerHTML = '';

                                                // 如果当前值不在API返回的选项中，先添加它
                                                if (currentScreenValue && !assemblyData.screenArray.some(item => item.screen === currentScreenValue)) {
                                                    const currentOption = document.createElement('option');
                                                    currentOption.value = currentScreenValue;
                                                    currentOption.textContent = currentScreenValue;
                                                    currentOption.selected = true;
                                                    screenSelect.appendChild(currentOption);
                                                }

                                                // 添加新的选项
                                                assemblyData.screenArray.forEach(item => {
                                                    const optionEl = document.createElement('option');
                                                    optionEl.value = item.screen;
                                                    optionEl.textContent = item.screen;
                                                    optionEl.selected = item.screen === currentScreenValue;
                                                    screenSelect.appendChild(optionEl);
                                                });

                                                // 设置选中值，优先使用当前值
                                                screenSelect.value = currentScreenValue || screenValue;
                                            }
                                        }

                                        // 更新TP字段
                                        if (assemblyData.tpArray && assemblyData.tpArray.length > 0) {
                                            const tpValue = assemblyData.tpArray[0].tp;
                                            this.setNestedValue(this.data, 'TP', tpValue);

                                            // 更新对应的DOM元素
                                            const tpSelect = this.container.querySelector(`select[data-field="TP"]`);
                                            if (tpSelect) {
                                                // 获取当前默认值（如果有）
                                                const currentTpValue = this.getNestedValue(this.data, 'TP') || '';
                                                
                                                // 清空现有选项
                                                tpSelect.innerHTML = '';

                                                // 如果当前值不在API返回的选项中，先添加它
                                                if (currentTpValue && !assemblyData.tpArray.some(item => item.tp === currentTpValue)) {
                                                    const currentOption = document.createElement('option');
                                                    currentOption.value = currentTpValue;
                                                    currentOption.textContent = currentTpValue;
                                                    currentOption.selected = true;
                                                    tpSelect.appendChild(currentOption);
                                                }

                                                // 添加新的选项
                                                assemblyData.tpArray.forEach(item => {
                                                    const optionEl = document.createElement('option');
                                                    optionEl.value = item.tp;
                                                    optionEl.textContent = item.tp;
                                                    optionEl.selected = item.tp === currentTpValue;
                                                    tpSelect.appendChild(optionEl);
                                                });

                                                // 设置选中值，优先使用当前值
                                                tpSelect.value = currentTpValue || tpValue;
                                            }
                                        }
                                    } catch (error) {
                                        console.error('获取装配数据失败:', error);
                                    }
                                }

                                // 处理其他linked_fields
                                field.linked_fields.forEach(linkedField => {
                                    // 如果不是分辨率字段的特殊处理，可以在这里添加通用的联动逻辑
                                });
                            }
                        });
                        break;

                    case 'radio':
                        // 创建滑动开关容器
                        const toggleContainer = document.createElement('div');
                        toggleContainer.className = 'toggle-container';

                        // 创建隐藏的单选按钮（用于表单数据）
                        const hiddenInput = document.createElement('input');
                        hiddenInput.type = 'hidden';
                        hiddenInput.value = currentValue;
                        this.inputElements.set(field.field, hiddenInput);

                        // 创建滑动开关
                        const toggleSwitch = document.createElement('label');
                        toggleSwitch.className = 'toggle-switch';

                        const checkbox = document.createElement('input');
                        checkbox.type = 'checkbox';
                        checkbox.checked = currentValue === 'on';

                        const slider = document.createElement('span');
                        slider.className = 'toggle-slider';

                        toggleSwitch.appendChild(checkbox);
                        toggleSwitch.appendChild(slider);

                        // 创建开关标签
                        const toggleLabels = document.createElement('div');
                        toggleLabels.className = 'toggle-labels';

                        toggleContainer.appendChild(toggleSwitch);
                        toggleContainer.appendChild(toggleLabels);
                        toggleContainer.appendChild(hiddenInput);

                        // 添加事件监听器
                        checkbox.addEventListener('change', (e) => {
                            const newValue = e.target.checked ? 'on' : 'off';
                            hiddenInput.value = newValue;
                            this.setNestedValue(this.data, field.field, newValue);

                            // 处理关联字段
                            if (this.linkedFields[field.field]) {
                                const linkedFieldPath = this.linkedFields[field.field];
                                this.setNestedValue(this.data, linkedFieldPath, newValue);
                                this.updateLinkedFieldInput(linkedFieldPath, newValue);
                            }
                        });

                        inputEl = toggleContainer;
                        break;

                case 'obj':
                    // 检测是否为PC端
                    const isPC = window.innerWidth >= 768;
                    // 获取对象值
                    let objValue = this.getNestedValue(this.data, field.field) || {};

                    // 关键修改：如果objValue为空，但有object_fields配置，初始化objValue
                    if (Object.keys(objValue).length === 0 && field.object_fields && field.object_fields.length > 0) {
                        console.log('[对象字段初始化] objValue为空，开始初始化...', field.field);
                        // 遍历object_fields，初始化每个字段
                        field.object_fields.forEach(fieldConfig => {
                            if (fieldConfig.field) {
                                let fieldValue;
                                // 优先使用field_path，否则构造完整路径
                                if (fieldConfig.field_path) {
                                    fieldValue = this.getNestedValue(this.data, fieldConfig.field_path);
                                } else {
                                    // 构造完整的嵌套路径
                                    const fullPath = `${field.field}.${fieldConfig.field}`;
                                    fieldValue = this.getNestedValue(this.data, fullPath);
                                }
                                
                                // 如果获取不到值，设为合适的默认值
                                if (fieldValue === undefined || fieldValue === null) {
                                    fieldValue = fieldConfig.input_type === 'image' && fieldConfig.multiple ? [] : '';
                                }
                                
                                objValue[fieldConfig.field] = fieldValue;
                                console.log(`[对象字段初始化] ${fieldConfig.field}:`, fieldValue, '类型:', fieldConfig.input_type);
                            }
                        });
                        // 保存初始化后的值，避免重复初始化
                        this.setNestedValue(this.data, field.field, objValue);
                        console.log('[对象字段初始化] 初始化完成，新objValue:', objValue);
                    }

                    // 如果对象为空，则隐藏标签和内容，但仍保留对象值
                    // 修改为：只有当没有配置object_fields时才隐藏
                    if (Object.keys(objValue).length === 0 && (!field.object_fields || field.object_fields.length === 0)) {
                        // 隐藏标签
                        labelEl.style.display = 'none';

                        // 隐藏内容
                        const emptyObjContainer = document.createElement('div');
                        inputEl = emptyObjContainer;
                        break;
                    }

                    // 显示标签（如果之前被隐藏）
                    labelEl.style.display = '';

                    // 如果是PC端，设置标签宽度
                    if (isPC) {
                        labelEl.style.width = '12px';
                    }

                    const objContainer = document.createElement('div');
                    objContainer.className = 'obj-container';
                    objContainer.style.width = '100%';
                    objContainer.style.boxSizing = 'border-box';
                    objContainer.style.border = '1px solid #ddd';
                    objContainer.style.borderRadius = '4px';
                    objContainer.style.padding = '15px';

                    // 移除了与showToggleLabel相关的代码

                    // 获取布局模式，默认为'block'（向后兼容）
                    const layoutMode = field.layout_mode || 'block';

                    // 键值对列表
                    const pairsList = document.createElement('div');
                    pairsList.className = 'pairs-list';

                    // 根据布局模式设置样式
                    if (layoutMode === 'inline') {
                        // 多个键值对在一行显示
                        pairsList.style.display = 'flex';
                        pairsList.style.flexWrap = 'nowrap'; // 修改为不换行
                        pairsList.style.gap = '5px'; // 减小间距
                        pairsList.style.width = '100%';
                    } else {
                        // 每个键值对单独一行显示
                        pairsList.style.display = 'block';
                    }
                    objContainer.appendChild(pairsList);


                    // 渲染键值对
                    const renderKeyValuePairs = () => {
                        // 保存现有的图片容器状态
                        const existingImageContainers = {};
                        pairsList.querySelectorAll('.image-upload-container').forEach(container => {
                            const key = container.getAttribute('data-key');
                            if (key) {
                                existingImageContainers[key] = {
                                    container: container,
                                    syncFunction: container._syncImageData
                                };
                            }
                        });
                        
                        pairsList.innerHTML = '';

                        Object.keys(objValue).forEach((key, index) => {
                            const value = objValue[key];
                            // 检查此键是否配置为允许空值
                            let allowEmpty = false;
                            if (field.object_fields && Array.isArray(field.object_fields)) {
                                const keyField = field.object_fields.find(f => f.field === key);
                                if (keyField && keyField.allow_empty !== undefined) {
                                    allowEmpty = keyField.allow_empty;
                                }
                            }

                            // 如果不允许空值，则跳过空值
                            // 修改：当点击显示所有按钮时，即使不允许空值也显示
                          /*   if (!allowEmpty && (value === '' || value === null || value === undefined)) {
                                return;
                            } */
                            
                            const pairContainer = document.createElement('div');
                            pairContainer.className = 'key-value-pair';

                            // 根据布局模式设置键值对容器样式
                            if (layoutMode === 'inline') {
                                // 多个键值对在一行显示（修改为键名与键值水平居中对齐）
                                pairContainer.style.display = 'flex';
                                pairContainer.style.flexDirection = 'row';  // 水平排列
                                pairContainer.style.alignItems = 'center';  // 垂直居中
                                pairContainer.style.marginBottom = '0';
                                pairContainer.style.marginRight = '5px'; // 减小右边距
                                pairContainer.style.minWidth = '0'; // 移除最小宽度限制
                                pairContainer.style.gap = '5px'; // 减小间隙
                                pairContainer.style.flex = '1 1 auto'; // 允许伸缩
                            } else {
                                // 每个键值对单独一行显示（键名与键值水平排列）
                                pairContainer.style.display = 'flex';
                                pairContainer.style.marginBottom = '10px';
                                pairContainer.style.alignItems = 'center';
                            }

                            // 在渲染键值对时，检查是否是通过添加按钮生成的
                            const isAddedKey = field.added_keys && field.added_keys[key];
                            // 键输入
                            const keyInput = document.createElement('input');
                            keyInput.type = 'text';
                            keyInput.value = key;
                            keyInput.style.padding = '8px';
                            keyInput.style.border = '1px solid #ddd';
                            keyInput.style.borderRadius = '4px 0 0 4px';
                            keyInput.style.boxSizing = 'border-box';
                            keyInput.style.display = 'flex';
                            keyInput.style.direction = 'row';
                            keyInput.style.paddingRight = '0';




                            keyInput.placeholder = '键';

                            // 根据布局模式设置键输入框样式
                            if (layoutMode === 'inline') {
                                // 多个键值对在一行显示
                                keyInput.style.flex = '0 0 auto'; // 不伸缩
                                keyInput.style.width = '60px';  // 设置固定宽度
                                keyInput.style.minWidth = '60px';  // 最小宽度也设置为相同值
                                keyInput.style.maxWidth = '80px'; // 最大宽
                                keyInput.style.marginBottom = '0';  // 去掉底部边距
                            } else {
                                // 每个键值对单独一行显示
                                keyInput.style.width = '20%';
                                keyInput.style.marginBottom = '0';
                            }

                            // 默认设置为可编辑
                            keyInput.readOnly = false;
                            // 设置默认背景色
                            keyInput.style.backgroundColor = '';

                            // 检查此键是否配置为禁止编辑
                            let keyEdit = false; // 默认允许编辑
                            if (field.object_fields && Array.isArray(field.object_fields)) {
                                const keyField = field.object_fields.find(f => f.field === key);
                                if (keyField && keyField.key_edit !== undefined) {
                                    keyEdit = keyField.key_edit;
                                }
                            }

                            // 如果禁止编辑且不是通过添加按钮生成的，则设置为只读并添加置灰背景
                            if (!keyEdit && !isAddedKey) {
                                keyInput.readOnly = true;
                                // 设置置灰背景色
                                keyInput.style.backgroundColor = '#f0f0f0';
                            }

                            // 只有通过添加按钮生成的键值对（以"新键"开头）才显示类型切换图标
                            let typeToggle = null;
                            if (key.startsWith('新键')) {
                                // 类型切换图标
                                typeToggle = document.createElement('div');
                                typeToggle.style.width = '30px';
                                typeToggle.style.height = '30px';
                                typeToggle.style.display = 'flex';
                                typeToggle.style.alignItems = 'center';
                                typeToggle.style.justifyContent = 'center';
                                typeToggle.style.border = '1px solid #ddd';
                                typeToggle.style.borderLeft = 'none';
                                typeToggle.style.borderRight = 'none';
                                typeToggle.style.cursor = 'pointer';
                                typeToggle.style.backgroundColor = '#f5f5f5';
                                typeToggle.title = '切换输入类型';

                                // 检查此键是否配置为图片或文件类型
                                let fieldType = 'text'; // 默认为文本类型
                                if (field.object_fields && Array.isArray(field.object_fields)) {
                                    const keyField = field.object_fields.find(f => f.field === key);
                                    if (keyField && keyField.input_type) {
                                        fieldType = keyField.input_type;
                                    }
                                }

                                // 根据当前类型设置图标
                                const updateTypeIcon = (type) => {
                                    typeToggle.innerHTML = '';
                                    const icon = document.createElement('span');
                                    icon.style.fontSize = '16px';
                                    
                                    switch (type) {
                                        case 'image':
                                            icon.innerHTML = '🖼️'; // 图片图标
                                            break;
                                        case 'file':
                                            icon.innerHTML = '📁'; // 文件图标
                                            break;
                                        default: // text
                                            icon.innerHTML = '🔤'; // 文本图标
                                    }
                                    
                                    typeToggle.appendChild(icon);
                                };

                                // 初始化图标
                                updateTypeIcon(fieldType);

                                // 类型切换事件
                                typeToggle.addEventListener('click', () => {
                                    // 切换类型: text -> image -> file -> text
                                    if (fieldType === 'text') {
                                        fieldType = 'image';
                                    } else if (fieldType === 'image') {
                                        fieldType = 'file';
                                    } else {
                                        fieldType = 'text';
                                    }
                                    
                                    // 更新图标
                                    updateTypeIcon(fieldType);
                                    
                                    // 更新字段配置
                                    if (!field.object_fields) {
                                        field.object_fields = [];
                                    }
                                    
                                    // 查找或创建字段配置
                                    let keyField = field.object_fields.find(f => f.field === key);
                                    if (!keyField) {
                                        keyField = { field: key, input_type: fieldType };
                                        field.object_fields.push(keyField);
                                    } else {
                                        keyField.input_type = fieldType;
                                    }
                                    
                                    // 重新渲染值输入组件
                                    renderValueInput();
                                });
                            }

                            // 分隔符
                            const separator = document.createElement('span');
                            separator.textContent = '';

                            // 根据布局模式设置分隔符
                            if (layoutMode === 'inline') {
                            // 多个键值对在一行显示时隐藏分隔符
                            separator.style.display = 'none';
                            } else {
                            // 每个键值对单独一行显示时显示分隔符
                            separator.style.padding = '0 10px';
                            separator.style.fontWeight = 'bold';
                            }

                            let valueInputContainer = document.createElement('div');

                            // 根据布局模式设置值输入容器样式
                            if (layoutMode === 'inline') {
                                // 多个键值对在一行显示
                                valueInputContainer.style.width = '100%';
                                valueInputContainer.style.flex = '1 1 100px';  // 允许扩展并设置基础宽度
                                valueInputContainer.style.minWidth = '100px';  // 设置最小宽度
                            }  else {
                                // 每个键值对单独一行显示
                                valueInputContainer.style.width = '100%';
                                valueInputContainer.style.minWidth = '200px';  // 为图片组件提供足够空间
                                valueInputContainer.style.display = 'flex';
                                valueInputContainer.style.flexDirection = 'row';
                                valueInputContainer.style.flexWrap = 'wrap';
                                valueInputContainer.style.gap = '5px';
                            }

                            // 渲染值输入组件
                            const renderValueInput = () => {
                                // 清空容器
                                valueInputContainer.innerHTML = '';
                                
                                let valueInput;
                                
                                // 获取字段配置
                                let keyField = field.object_fields && field.object_fields.find(f => f.field === key);
                                // 使用field_path获取值，如果存在
                                const valuePath = keyField && keyField.field_path ? keyField.field_path : `${field.field}.${key}`;
                                const value = keyField && keyField.field_path ? 
                                              this.getNestedValue(this.data, keyField.field_path) : objValue[key];
                                
                                // 添加关键调试信息
                                console.log('对象字段路径构造:', {
                                    field_field: field.field,
                                    key: key,
                                    keyField_field_path: keyField?.field_path,
                                    最终valuePath: valuePath,
                                    当前值: value,
                                    objValue_key: objValue[key]
                                });
                                
                                // 检查此键是否配置为图片或文件类型
                                let fieldType = 'text'; // 默认为文本类型
                                if (keyField && keyField.input_type) {
                                    fieldType = keyField.input_type;
                                }
                                
                                // 根据字段类型创建相应的输入组件
                                switch (fieldType) {
                                    case 'image':
                                        // 使用封装的createImageUploadComponent方法创建图片上传组件
                                        const imageField = {
                                            field: valuePath,  // 这里使用完整的嵌套路径
                                            // 传递keyField的所有配置属性，包括multiple、galleryData等
                                            ...keyField
                                        };
                                        console.log('创建obj图片字段:', valuePath, '配置:', imageField);
                                        console.log('obj图片字段当前值:', value);
                                        console.log('obj图片字段keyField配置:', keyField);
                                        console.log('字段路径构造详情 - field.field:', field.field, 'key:', key, 'keyField.field:', keyField?.field);
                                        
                                        // 检查是否有现有的图片容器可以复用
                                        let imageContainer;
                                        if (existingImageContainers[key] && existingImageContainers[key].container) {
                                            console.log('复用现有图片容器:', key);
                                            imageContainer = existingImageContainers[key].container;
                                            // 重新设置同步函数
                                            imageContainer._syncImageData = existingImageContainers[key].syncFunction;
                                        } else {
                                            console.log('创建新图片容器:', key);
                                            imageContainer = this.createImageUploadComponent(imageField, value);
                                        }
                                        
                                        // 为图片容器添加键标识
                                        imageContainer.setAttribute('data-key', key);
                                        
                                        // 重要修复：为图片组件添加自定义数据同步逻辑
                                        const syncImageData = (newValue) => {
                                            console.log('同步图片数据 - valuePath:', valuePath, '新值:', newValue);
                                            
                                            // 1. 更新嵌套路径
                                            this.setNestedValue(this.data, valuePath, newValue);
                                            
                                            // 2. 更新对象局部值（重要！）
                                            objValue[key] = newValue;
                                            this.setNestedValue(this.data, field.field, objValue);
                                            
                                            // 3. 如果有field_path配置，也要更新
                                            if (keyField && keyField.field_path) {
                                                this.setNestedValue(this.data, keyField.field_path, newValue);
                                            }
                                            
                                            console.log('同步完成，数据状态:', {
                                                嵌套路径值: this.getNestedValue(this.data, valuePath),
                                                对象局部值: objValue[key],
                                                field_path值: keyField?.field_path ? this.getNestedValue(this.data, keyField.field_path) : 'N/A'
                                            });
                                        };
                                        
                                        // 为图片容器添加数据变化监听
                                        imageContainer.addEventListener('change', (event) => {
                                            if (event.target && event.target.classList.contains('image-upload-input')) {
                                                // 文件上传后的处理将在handleFileChange中触发
                                                console.log('检测到图片文件变化');
                                            }
                                        });
                                        
                                        // 保存同步函数到容器上，供其他方法调用
                                        imageContainer._syncImageData = syncImageData;
                                        valueInput = imageContainer;
                                        break;
                                    case 'file':
                                        // 使用封装的createFileUploadComponent方法创建文件上传组件
                                        const fileField = {
                                            field: valuePath,
                                            // 可以根据需要添加其他属性，如accept等
                                        };
                                        const fileContainer = this.createFileUploadComponent(fileField, value);
                                        valueInput = fileContainer;
                                        break;
                                    case 'select':
                                        // 创建下拉选择框
                                        valueInput = document.createElement('select');
                                        valueInput.style.width = '120px';
                                        valueInput.style.padding = '8px';
                                        valueInput.style.border = '1px solid #ddd';
                                        valueInput.style.borderRadius = '0';
                                        valueInput.style.boxSizing = 'border-box';
                                        
                                        // 添加attrs属性支持
                                        if (keyField && keyField.attrs && typeof keyField.attrs === 'object') {
                                            Object.keys(keyField.attrs).forEach(attrKey => {
                                                valueInput.setAttribute(attrKey, keyField.attrs[attrKey]);
                                            });
                                        }

                                        // 如果有关联选项配置，添加选项
                                        if (keyField && keyField.options && keyField.options.length) {
                                            keyField.options.forEach(option => {
                                                const optionEl = document.createElement('option');
                                                optionEl.value = option;
                                                optionEl.textContent = option;
                                                optionEl.selected = value === option;
                                                valueInput.appendChild(optionEl);
                                            });
                                        }
                                        
                                        // 存储输入元素引用
                                        if (keyField && keyField.field_path) {
                                            this.inputElements.set(keyField.field_path, valueInput);
                                        }
                                        
                                        // 添加change事件监听器
                                        if (keyField && keyField.field_path) {
                                            valueInput.addEventListener('change', () => {
                                                const selectedValue = valueInput.value;
                                                this.setNestedValue(this.data, keyField.field_path, selectedValue);
                                                
                                                // 处理关联字段同步
                                                if (this.linkedFields[keyField.field_path]) {
                                                    const linkedFieldPath = this.linkedFields[keyField.field_path];
                                                    this.setNestedValue(this.data, linkedFieldPath, selectedValue);
                                                    this.updateLinkedFieldInput(linkedFieldPath, selectedValue);
                                                }
                                            });
                                        } else {
                                            valueInput.addEventListener('change', () => {
                                                objValue[key] = valueInput.value;
                                                this.setNestedValue(this.data, field.field, objValue);
                                            });
                                        }
                                        break;
                                    default:
                                        // 普通文本输入框
                                        valueInput = document.createElement('input');
                                        valueInput.type = 'text';
                                        valueInput.value = value;
                                        valueInput.style.width = '100%';
                                        valueInput.style.padding = '8px';
                                        valueInput.style.border = '1px solid #ddd';
                                        valueInput.style.borderRadius = '0';
                                        valueInput.style.boxSizing = 'border-box';
                                        valueInput.placeholder = '值';

                                        // 添加这行代码，存储输入元素引用
                                        if (keyField && keyField.field_path) {
                                            this.inputElements.set(keyField.field_path, valueInput);
                                        }
                                        
                                        if (keyField && keyField.field_path) {
                                            // 使用field_path更新值
                                            valueInput.addEventListener('input', () => {
                                                this.setNestedValue(this.data, keyField.field_path, valueInput.value);
                                                
                                                // 添加关联字段处理逻辑
                                                if (this.linkedFields[keyField.field_path]) {
                                                    const linkedFieldPath = this.linkedFields[keyField.field_path];
                                                    this.setNestedValue(this.data, linkedFieldPath, valueInput.value);
                                                    this.updateLinkedFieldInput(linkedFieldPath, valueInput.value);
                                                }
                                            });
                                        } else {
                                            // 原来的逻辑
                                            valueInput.addEventListener('input', () => {
                                                objValue[key] = valueInput.value;
                                                this.setNestedValue(this.data, field.field, objValue);
                                            });
                                        }
                                }
                                
                                valueInputContainer.appendChild(valueInput);
                            };

                            // 初始化值输入组件
                            renderValueInput();

                            // 删除按钮
                            const deleteBtn = document.createElement('button');
                            deleteBtn.textContent = '删除';
                            deleteBtn.style.fontSize = '14px';
                            deleteBtn.style.width = '70px';
                            deleteBtn.style.height = '30px';
                            deleteBtn.style.backgroundColor = '#f44336';
                            deleteBtn.style.color = 'white';
                            deleteBtn.style.border = 'none';
                            deleteBtn.style.padding = '5px 10px';
                            deleteBtn.style.borderRadius = '4px';
                            deleteBtn.style.cursor = 'pointer';
                            deleteBtn.style.textAlign = 'center';
                            deleteBtn.style.display = 'inline-block';
                            
                            // 检查此键是否配置为隐藏删除按钮
                            let showDelete = false; // 默认隐藏

                            // 检查是否是通过"添加内容"按钮添加的键值对(键名以"新键"开头)
                            if (key.startsWith('新键')) {
                                showDelete = true; // 通过"添加内容"按钮添加的键值对默认显示删除按钮
                            } else if (field.object_fields && Array.isArray(field.object_fields)) {
                                // 对于其他键值对，根据配置控制显示/隐藏
                                const keyField = field.object_fields.find(f => f.field === key);
                                if (keyField && keyField.show_delete !== undefined) {
                                    showDelete = keyField.show_delete;
                                }
                            }
                            
                            // 根据配置控制删除按钮显示
                            deleteBtn.style.display = showDelete ? 'inline-block' : 'none';

                        // 事件监听
                            keyInput.addEventListener('change', () => {
                                // 只有在允许编辑时才执行键名更新逻辑
                                if (keyEdit || isAddedKey) {
                                    const newKey = keyInput.value.trim();
                                    if (newKey && newKey !== key) {
                                        // 检查新键名是否已经存在
                                        if (!objValue.hasOwnProperty(newKey)) {
                                            // 更新键名，删除旧键
                                            objValue[newKey] = objValue[key];
                                            delete objValue[key]; // 取消注释这行以删除旧键
                                            this.setNestedValue(this.data, field.field, objValue);
                                            
                                            // 更新added_keys标记
                                            if (isAddedKey) {
                                                delete field.added_keys[key];
                                                field.added_keys[newKey] = true;
                                            }
                                        }
                                    }
                                    // 重新渲染键值对
                                    renderKeyValuePairs();
                                }
                            });

                            deleteBtn.addEventListener('click', () => {
                                // 删除键值对
                                delete objValue[key];
                                this.setNestedValue(this.data, field.field, objValue);
                                // 重新渲染键值对
                                renderKeyValuePairs();
                            });

                            pairContainer.appendChild(keyInput);
                            // 只有通过添加按钮生成的键值对才添加类型切换图标
                            if (typeToggle) {
                                pairContainer.appendChild(typeToggle);
                            }
                            pairContainer.appendChild(separator);
                            pairContainer.appendChild(valueInputContainer);
                            pairContainer.appendChild(deleteBtn);
                            pairsList.appendChild(pairContainer);
                        });
                    };

                    // 检查是否需要显示添加按钮
                    const showAddButton = field.show_add_button !== undefined ? field.show_add_button : true; // 默认显示
                    const addButtonText = field.add_button_text || '+添加'; // 默认文案

                    // 只有在需要显示时才创建添加按钮
                    if (showAddButton) {
                        // 添加新键值对按钮
                        const addButton = document.createElement('button');
                        addButton.textContent = addButtonText;
                        addButton.style.marginTop = '10px';
                        addButton.style.backgroundColor = '#3b82f6'; // 改为指定颜色
                        addButton.style.color = 'white';
                        addButton.style.border = 'none';
                        addButton.style.borderRadius = '4px';
                        addButton.style.cursor = 'pointer';
                        addButton.style.float = 'right'; // 靠右对齐
                        addButton.style.padding = '5px 10px'; // 调整内边距

                        // 在添加按钮的点击事件处理程序中，为新创建的键值对添加一个标记
                        addButton.addEventListener('click', () => {
                            // 查找一个未使用的键名
                            let newKey = '新键';
                            let counter = 1;
                            while (objValue.hasOwnProperty(newKey)) {
                                newKey = `新键${counter}`;
                                counter++;
                            }
                            objValue[newKey] = '请输入值'; // 设置非空默认值
                            
                            // 为通过添加按钮生成的键值对添加一个标记
                            if (!field.added_keys) {
                                field.added_keys = {};
                            }
                            field.added_keys[newKey] = true;
                            
                            this.setNestedValue(this.data, field.field, objValue);
                            renderKeyValuePairs();
                        });

                        objContainer.appendChild(addButton);
                    }

                    // 初始渲染
                    renderKeyValuePairs();

                    inputEl = objContainer;
                    break;


                    case 'doubleselect':
                        // 创建doubleselect容器
                        const doubleSelectContainer = document.createElement('div');
                        doubleSelectContainer.className = 'double-select-container';
                        doubleSelectContainer.style.display = 'flex';
                        doubleSelectContainer.style.gap = '0';
                        doubleSelectContainer.style.width = '100%';

                        // 左侧列表容器
                        const leftContainer = document.createElement('div');
                        leftContainer.style.flex = '1';
                        leftContainer.style.margin = '0';
                        leftContainer.style.padding = '0';

                        const leftLabel = document.createElement('label');
                        leftLabel.textContent = field.left_label || '支持语言';
                        leftLabel.style.margin = '0 0 1px 0';
                        leftLabel.style.fontSize = '14px';
                        leftContainer.appendChild(leftLabel);

                        // 使用div模拟select的多列显示
                        const leftSelect = document.createElement('div');
                        leftSelect.style.width = '100%';
                        leftSelect.style.height = '180px';
                        leftSelect.style.border = '1px solid #d1d5db';
                        leftSelect.style.borderRadius = '2px';
                        leftSelect.style.overflowY = 'auto';
                        leftSelect.style.display = 'grid';
                        leftSelect.style.gridTemplateColumns = 'repeat(auto-fill, minmax(70px, 1fr))';
                        leftSelect.style.gap = '1px';  // 保持微小间距
                        leftSelect.style.padding = '1px';  // 保持微小内边距
                        leftSelect.style.margin = '0';
                        leftSelect.style.alignContent = 'flex-start';
                        leftContainer.appendChild(leftSelect);

                        // 操作按钮容器
                        const buttonContainer = document.createElement('div');
                        buttonContainer.style.display = 'flex';
                        buttonContainer.style.flexDirection = 'column';
                        buttonContainer.style.justifyContent = 'center';
                        buttonContainer.style.gap = '0';
                        buttonContainer.style.flex = '0 0 auto';
                        buttonContainer.style.margin = '0';
                        buttonContainer.style.padding = '0';
                        buttonContainer.style.width = 'fit-content';

                        // 添加按钮（使用唯一变量名）
                        const doubleSelectAddBtn = document.createElement('button');
                        doubleSelectAddBtn.textContent = '<<';
                        doubleSelectAddBtn.style.backgroundColor = '#2c6ecb';
                        doubleSelectAddBtn.style.color = 'white';
                        doubleSelectAddBtn.style.padding = '2px 2px';
                        doubleSelectAddBtn.style.margin = '1px 0';
                        doubleSelectAddBtn.style.fontSize = '12px';
                        doubleSelectAddBtn.style.width = 'fit-content';

                        // 删除按钮（使用唯一变量名）
                        const doubleSelectRemoveBtn = document.createElement('button');
                        doubleSelectRemoveBtn.textContent = '>>';
                        doubleSelectRemoveBtn.style.color = 'white';
                        doubleSelectRemoveBtn.style.padding = '2px 2px';
                        doubleSelectRemoveBtn.style.margin = '1px 0';
                        doubleSelectRemoveBtn.style.fontSize = '12px';
                        doubleSelectRemoveBtn.style.width = 'fit-content';
                        doubleSelectRemoveBtn.style.backgroundColor = '#FF4757';


                        buttonContainer.appendChild(doubleSelectAddBtn);
                        buttonContainer.appendChild(doubleSelectRemoveBtn);

                        // 右侧列表容器
                        const rightContainer = document.createElement('div');
                        rightContainer.style.flex = '1';
                        rightContainer.style.margin = '0';
                        rightContainer.style.padding = '0';

                        const rightLabel = document.createElement('label');
                        rightLabel.textContent = field.right_label || '不支持语言';
                        rightLabel.style.margin = '0 0 1px 0';
                        rightLabel.style.fontSize = '14px';
                        rightContainer.appendChild(rightLabel);

                        // 使用div模拟select的多列显示
                        const rightSelect = document.createElement('div');
                        rightSelect.style.width = '100%';
                        rightSelect.style.height = '180px';
                        rightSelect.style.border = '1px solid #d1d5db';
                        rightSelect.style.borderRadius = '2px';
                        rightSelect.style.overflowY = 'auto';
                        rightSelect.style.display = 'grid';
                        rightSelect.style.gridTemplateColumns = 'repeat(auto-fill, minmax(80px, 1fr))';
                        rightSelect.style.gap = '1px';  // 保持微小间距
                        rightSelect.style.padding = '1px';  // 保持微小内边距
                        rightSelect.style.margin = '0';
                        rightSelect.style.alignContent = 'flex-start';
                        rightContainer.appendChild(rightSelect);

                        // 组装容器
                        doubleSelectContainer.appendChild(leftContainer);
                        doubleSelectContainer.appendChild(buttonContainer);
                        doubleSelectContainer.appendChild(rightContainer);

                        // 获取数据
                        const allItems = field.all_items || [];
                        const selectedItems = Array.isArray(currentValue) ? currentValue : [];

                        // 过滤出未选择的项目
                        const unselectedItems = allItems.filter(item => !selectedItems.includes(item));

                        // 填充右侧列表（未选择的项目）
                        unselectedItems.forEach(item => {
                            const option = document.createElement('div');
                            option.textContent = item;
                            // 关键修改：使文案大小与背景大小一致
                            option.style.padding = '2px 2px';  // 减小内边距
                            option.style.border = '1px solid transparent';
                            option.style.borderRadius = '2px';  // 减小圆角
                            option.style.cursor = 'pointer';
                            option.style.userSelect = 'none';
                            option.style.fontSize = '12px';  // 统一字体大小
                            option.style.lineHeight = '1.2';  // 调整行高
                            option.style.boxSizing = 'border-box';  // 使用border-box模型
                            option.style.width = '100%';  // 占满网格单元格
                            option.style.textAlign = 'center';  // 文本居中
                            option.dataset.value = item;

                            // 添加选中效果 - 允许多选
                            option.addEventListener('click', function () {
                                if (this.style.backgroundColor === 'rgb(44, 110, 203)' || this.style.backgroundColor === '#2c6ecb') {
                                    // 取消选中
                                    this.style.backgroundColor = '';
                                    this.style.color = '';
                                } else {
                                    // 选中
                                    this.style.backgroundColor = '#2c6ecb';
                                    this.style.color = 'white';
                                }
                            });

                            rightSelect.appendChild(option);
                        });

                        // 填充左侧列表（已选择的项目）
                        selectedItems.forEach(item => {
                            const option = document.createElement('div');
                            option.textContent = item;
                            // 关键修改：使文案大小与背景大小一致
                            option.style.padding = '2px 2px';  // 减小内边距
                            option.style.border = '1px solid transparent';
                            option.style.borderRadius = '2px';  // 减小圆角
                            option.style.cursor = 'pointer';
                            option.style.userSelect = 'none';
                            option.style.fontSize = '12px';  // 统一字体大小
                            option.style.lineHeight = '1.2';  // 调整行高
                            option.style.boxSizing = 'border-box';  // 使用border-box模型
                            option.style.width = '100%';  // 占满网格单元格
                            option.style.textAlign = 'center';  // 文本居中
                            option.dataset.value = item;

                            // 添加选中效果 - 允许多选
                            option.addEventListener('click', function () {
                                if (this.style.backgroundColor === 'rgb(255, 71, 87)' || this.style.backgroundColor === '#FF4757') {
                                    // 取消选中
                                    this.style.backgroundColor = '';
                                    this.style.color = '';
                                } else {
                                    // 选中
                                    this.style.backgroundColor = '#FF4757';
                                    this.style.color = 'white';
                                }
                            });

                            leftSelect.appendChild(option);
                        });

                        // 添加事件监听器
                        doubleSelectAddBtn.addEventListener('click', () => {
                            // 获取右侧列表中所有选中的选项
                            const selectedOptions = Array.from(rightSelect.children).filter(option =>
                                option.style.backgroundColor === 'rgb(44, 110, 203)' ||
                                option.style.backgroundColor === '#2c6ecb');

                            selectedOptions.forEach(option => {
                                // 保存选项的值
                                const optionValue = option.dataset.value;

                                // 从右侧列表移除
                                rightSelect.removeChild(option);

                                // 创建新的选项元素
                                const newOption = document.createElement('div');
                                newOption.textContent = optionValue;
                                newOption.style.backgroundColor = '';  // 初始设为未选中
                                newOption.style.color = '';
                                newOption.style.padding = '2px 2px';
                                newOption.style.border = '1px solid transparent';
                                newOption.style.borderRadius = '2px';
                                newOption.style.cursor = 'pointer';
                                newOption.style.userSelect = 'none';
                                newOption.style.fontSize = '12px';
                                newOption.style.lineHeight = '1.2';
                                newOption.style.boxSizing = 'border-box';
                                newOption.style.width = '100%';
                                newOption.style.textAlign = 'center';
                                newOption.dataset.value = optionValue;

                                // 添加左侧选项的点击事件 - 允许多选
                                newOption.addEventListener('click', function () {
                                    if (this.style.backgroundColor === 'rgb(255, 71, 87)' || this.style.backgroundColor === '#FF4757') {
                                        // 取消选中
                                        this.style.backgroundColor = '';
                                        this.style.color = '';
                                    } else {
                                        // 选中
                                        this.style.backgroundColor = '#FF4757';
                                        this.style.color = 'white';
                                    }
                                });

                                // 将新选项添加到左侧列表
                                leftSelect.appendChild(newOption);
                            });

                            // 更新数据
                            /* const updateDoubleSelectValue = () => {
                                const selectedValues = Array.from(leftSelect.children).map(option => option.dataset.value);
                                this.setNestedValue(this.data, field.field, selectedValues);
                            }; */
                            updateDoubleSelectValue();
                        });

                        doubleSelectRemoveBtn.addEventListener('click', () => {
                            // 获取左侧列表中所有选中的选项
                            const selectedOptions = Array.from(leftSelect.children).filter(option =>
                                option.style.backgroundColor === 'rgb(255, 71, 87)' ||
                                option.style.backgroundColor === '#FF4757');

                            selectedOptions.forEach(option => {
                                // 保存选项的值
                                const optionValue = option.dataset.value;

                                // 从左侧列表移除
                                leftSelect.removeChild(option);

                                // 创建新的选项元素
                                const newOption = document.createElement('div');
                                newOption.textContent = optionValue;
                                newOption.style.backgroundColor = '';  // 初始设为未选中
                                newOption.style.color = '';
                                newOption.style.padding = '2px 2px';
                                newOption.style.border = '1px solid transparent';
                                newOption.style.borderRadius = '2px';
                                newOption.style.cursor = 'pointer';
                                newOption.style.userSelect = 'none';
                                newOption.style.fontSize = '12px';
                                newOption.style.lineHeight = '1.2';
                                newOption.style.boxSizing = 'border-box';
                                newOption.style.width = '100%';
                                newOption.style.textAlign = 'center';
                                newOption.dataset.value = optionValue;

                                // 添加右侧选项的点击事件 - 允许多选
                                newOption.addEventListener('click', function () {
                                    if (this.style.backgroundColor === 'rgb(44, 110, 203)' || this.style.backgroundColor === '#2c6ecb') {
                                        // 取消选中
                                        this.style.backgroundColor = '';
                                        this.style.color = '';
                                    } else {
                                        // 选中
                                        this.style.backgroundColor = '#2c6ecb';
                                        this.style.color = 'white';
                                    }
                                });

                                // 将新选项添加到右侧列表
                                rightSelect.appendChild(newOption);
                            });

                            // 更新数据
                            /* const updateDoubleSelectValue = () => {
                                const selectedValues = Array.from(leftSelect.children).map(option => option.dataset.value);
                                this.setNestedValue(this.data, field.field, selectedValues);
                            }; */
                            updateDoubleSelectValue();
                        });

                        // 更新数据值的函数 - 使用箭头函数继承外部this上下文
                        const updateDoubleSelectValue = () => {

                            const selectedValues = Array.from(leftSelect.children).map(option => option.dataset.value);
                            console.log('选中的值列表:', selectedValues);
                            this.setNestedValue(this.data, field.field, selectedValues);
                            console.log('更新数据路径:', field.field, '值:', selectedValues);

                            // 检查是否是支持语言字段，如果是则更新默认语言的选项
                            if (field.field === '软件配置V2.语言.支持语言') {
                                const defaultLangPath = '软件配置V2.语言.默认语言';

                                // 查找默认语言字段配置
                                let defaultLangField = null;
                                Object.values(this.categories).forEach(category => {
                                    const found = category.find(f => f.field === defaultLangPath);
                                    if (found) {
                                        defaultLangField = found;
                                        // 更新默认语言字段的选项
                                        defaultLangField.options = selectedValues;
                                        console.log('更新默认语言选项为:', selectedValues);
                                    }
                                });

                                // 检查当前默认语言是否在新的支持列表中
                                const currentDefaultLang = this.getNestedValue(this.data, defaultLangPath);
                                if (!selectedValues.includes(currentDefaultLang) && selectedValues.length > 0) {
                                    let newDefaultLang;
                                    // 优先选择英语
                                    if (selectedValues.includes('英语')) {
                                        newDefaultLang = '英语';
                                    } else {
                                        // 如果英语不存在，选择数组第一个元素
                                        newDefaultLang = selectedValues[0];
                                    }
                                    // 更新默认语言值
                                    this.setNestedValue(this.data, defaultLangPath, newDefaultLang);


                                    // 只有当默认语言实际发生变化时才显示toast提示
                                    if (currentDefaultLang !== newDefaultLang) {
                                        if (window.layer) {
                                            layer.msg(`默认语言已更新为: ${newDefaultLang}`, {
                                                icon: 1,
                                                time: 2000 // 2秒后自动关闭
                                            });
                                            console.log('显示toast提示: 默认语言已更新');
                                        } else {
                                            console.log('layer库不可用，无法显示toast提示');
                                        }
                                    } else {
                                        console.log('默认语言未变化，不显示提示');
                                    }

                                    // 尝试重新渲染表单
                                    this.renderForm();
                                    console.log('触发表单重新渲染以更新默认语言显示');

                                    // 额外检查：确认数据是否被正确更新
                                    const updatedDefaultLang = this.getNestedValue(this.data, defaultLangPath);
                                    console.log('确认更新后默认语言:', updatedDefaultLang);
                                }
                            }

                            // 检查是否有关联字段需要同步更新
                            if (this.linkedFields && this.linkedFields[field.field]) {
                                const linkedFieldPath = this.linkedFields[field.field];

                                // 如果关联字段是默认语言，确保只更新其options而不是值
                                if (linkedFieldPath === '软件配置V2.语言.默认语言') {
                                    // 查找默认语言字段配置并更新options
                                    let defaultLangField = null;
                                    Object.values(this.categories).forEach(category => {
                                        const found = category.find(f => f.field === linkedFieldPath);
                                        if (found) {
                                            defaultLangField = found;
                                            // 确保selectedValues是数组格式
                                            if (!Array.isArray(selectedValues)) {
                                                selectedValues = [selectedValues];
                                                console.log('转换selectedValues为数组:', selectedValues);
                                            }
                                            // 保存旧的选项以便比较
                                            const oldOptions = [...(defaultLangField.options || [])];
                                            defaultLangField.options = selectedValues;
                                            console.log('更新关联字段选项:', linkedFieldPath, '旧值:', oldOptions, '新值:', selectedValues);
                                        }
                                    });

                                    // 强制更新默认语言字段的UI
                                    if (defaultLangField) {
                                        console.log('准备强制更新默认语言字段UI');
                                        
                                        // 方法1: 尝试直接更新select元素的options
                                        const updateSelectOptions = () => {
                                            const selectElement = document.querySelector(`[data-field-path="${linkedFieldPath}"] select`);
                                            if (selectElement) {
                                                console.log('找到select元素，直接更新options');
                                                // 清空现有选项
                                                selectElement.innerHTML = '';
                                                // 添加新选项
                                                defaultLangField.options.forEach(option => {
                                                    const opt = document.createElement('option');
                                                    opt.value = option;
                                                    opt.textContent = option;
                                                    // 设置选中状态
                                                    if (option === this.getNestedValue(this.data, linkedFieldPath)) {
                                                        opt.selected = true;
                                                    }
                                                    selectElement.appendChild(opt);
                                                });
                                                console.log('直接更新select options成功');
                                                // 触发change事件
                                                const event = new Event('change', { bubbles: true });
                                                selectElement.dispatchEvent(event);
                                                return true;
                                            }
                                            return false;
                                        };

                                        // 先尝试直接更新选项
                                        if (!updateSelectOptions()) {
                                            console.log('直接更新options失败，尝试重新渲染整个字段');
                                            // 查找默认语言字段的DOM元素
                                            const defaultLangElement = document.querySelector(`[data-field-path="${linkedFieldPath}"]`);
                                            console.log('查找默认语言DOM元素:', defaultLangElement);

                                            if (defaultLangElement) {
                                                // 获取父容器
                                                const parentElement = defaultLangElement.parentNode;
                                                // 移除旧元素
                                                parentElement.removeChild(defaultLangElement);
                                                console.log('已移除旧的默认语言字段DOM元素');
                                                // 重新渲染字段
                                                setTimeout(() => {
                                                    const newElement = this.renderField(defaultLangField);
                                                    console.log('重新渲染字段结果:', newElement);
                                                    // 添加到容器
                                                    parentElement.appendChild(newElement);
                                                    console.log('强制更新默认语言字段UI成功');

                                                    // 额外确保数据绑定正确
                                                    setTimeout(() => {
                                                        const updatedElement = document.querySelector(`[data-field-path="${linkedFieldPath}"]`);
                                                        if (updatedElement) {
                                                            console.log('确认更新后的DOM元素存在');
                                                            // 触发change事件确保值同步
                                                            const event = new Event('change', { bubbles: true });
                                                            updatedElement.dispatchEvent(event);
                                                        }
                                                    }, 100);
                                                }, 50);
                                            } else {
                                                console.log('未找到默认语言字段的DOM元素');
                                                // 尝试使用更宽松的选择器
                                                const alternativeElement = document.querySelector(`[data-field-path*="${linkedFieldPath.split('.').join('\\.')}"]`);
                                                if (alternativeElement) {
                                                    console.log('使用替代选择器找到DOM元素');
                                                    const parentElement = alternativeElement.parentNode;
                                                    parentElement.removeChild(alternativeElement);
                                                    setTimeout(() => {
                                                        const newElement = this.renderField(defaultLangField);
                                                        parentElement.appendChild(newElement);
                                                        console.log('使用替代选择器强制更新UI成功');
                                                    }, 50);
                                                } else {
                                                    console.log('所有选择器都无法找到DOM元素，更新失败');
                                                    // 作为最后的手段，尝试重新渲染整个表单
                                                    setTimeout(() => {
                                                        console.log('尝试重新渲染整个表单');
                                                        this.renderForm();
                                                    }, 100);
                                                }
                                            }
                                        }
                                    }
                                } else {
                                    // 对于其他关联字段，正常更新值
                                    this.setNestedValue(this.data, linkedFieldPath, selectedValues);
                                    console.log('更新关联字段:', linkedFieldPath, '值:', selectedValues);
                                }
                            } else {
                                console.log('没有找到关联字段或field.field为空:', field.field);
                            }
                            // alert(5555) // 注释掉测试用的alert
                        };


                        inputEl = doubleSelectContainer;
                        break;
                    case 'objradio':
                        // 检测是否为PC端
                        if (window.innerWidth >= 768) {
                            labelEl.style.width = '12px';
                        }
                        const objRadioContainer = document.createElement('div');
                        objRadioContainer.className = 'object-radio-container';
                        objRadioContainer.style.width = '100%';
                        objRadioContainer.style.boxSizing = 'border-box';

                        // 获取当前对象值
                        let currentObjRadioValue = this.getNestedValue(this.data, field.field) || {};

                        // 动态获取object_fields
                        let objRadioFields = field.object_fields || [];

                        // 如果没有明确指定object_fields，但field有default_value，则从default_value生成
                        if (objRadioFields.length === 0 && field.default_value && typeof field.default_value === 'object') {
                            objRadioFields = Object.keys(field.default_value).map(key => ({
                                'field': key,
                                'label': key
                            }));
                        }

                        // 新增：如果仍然没有字段定义，则从当前数据生成
                        if (objRadioFields.length === 0 && currentObjRadioValue && typeof currentObjRadioValue === 'object') {
                            objRadioFields = Object.keys(currentObjRadioValue).map(key => ({
                                'field': key,
                                'label': key
                            }));
                        }

                        // 创建滑动开关容器
                        const switchesContainer = document.createElement('div');
                        switchesContainer.className = 'switches-container';
                        switchesContainer.style.display = 'flex';
                        switchesContainer.style.flexWrap = 'wrap';
                        switchesContainer.style.gap = '15px';
                        switchesContainer.style.marginTop = '10px';
                        // 在renderObjRadioFields函数外部定义一个对象来保存每个输入框的状态
                        const inputStates = {};

                        const renderObjRadioFields = () => {
                            // 清空现有内容
                            switchesContainer.innerHTML = '';

                            // 渲染对象字段（每个字段使用滑动开关）
                            objRadioFields.forEach((subField, index) => {
                                const switchWrapper = document.createElement('div');
                                switchWrapper.className = 'switch-wrapper';
                                switchWrapper.style.display = 'flex';
                                switchWrapper.style.alignItems = 'center';
                                switchWrapper.style.gap = '8px';
                                switchWrapper.style.padding = '8px';
                                switchWrapper.style.border = '1px solid #ddd';
                                switchWrapper.style.borderRadius = '4px';
                                switchWrapper.style.backgroundColor = '#f9f9f9';

                                // 创建可编辑的输入框替代静态标签
                                const labelInput = document.createElement('input');
                                labelInput.type = 'text';
                                labelInput.value = subField.label !== undefined ? subField.label : '';
                                labelInput.style.fontWeight = 'normal';
                                labelInput.style.marginRight = '5px';
                                labelInput.style.whiteSpace = 'nowrap';
                                labelInput.style.border = '1px solid #ccc';
                                labelInput.style.borderRadius = '4px';
                                labelInput.style.padding = '2px 5px';
                                labelInput.style.width = '120px';

                                // 创建提示文案元素
                                const warningText = document.createElement('div');
                                warningText.textContent = '存在相同的配置';

                                warningText.style.color = 'red';
                                warningText.style.fontSize = '12px';
                                warningText.style.marginTop = '2px';
                                warningText.style.display = 'none'; // 默认隐藏

                                // 添加输入事件处理
                                labelInput.addEventListener('input', (e) => {
                                    // 获取所有其他输入框的值（排除当前输入框）
                                    const allInputs = switchesContainer.querySelectorAll('input[type="text"]');
                                    const otherValues = Array.from(allInputs)
                                        .filter(input => input !== e.target)
                                        .map(input => input.value);

                                    // 检查当前输入值是否与其它输入框重复
                                    if (otherValues.includes(e.target.value)) {
                                        // 如果重复，标红边框并显示提示文案
                                        e.target.style.border = '2px solid red';
                                        warningText.style.display = 'block';
                                        // 保存状态
                                        inputStates[subField.field] = {
                                            isDuplicate: true,
                                            border: '2px solid red',
                                            warningDisplay: 'block'
                                        };
                                    } else {
                                        // 如果不重复，恢复默认边框并隐藏提示文案
                                        e.target.style.border = '1px solid #ccc';
                                        warningText.style.display = 'none';
                                        // 保存状态
                                        inputStates[subField.field] = {
                                            isDuplicate: false,
                                            border: '1px solid #ccc',
                                            warningDisplay: 'none'
                                        };
                                    }

                                    // 更新objRadioFields中的label
                                    subField.label = e.target.value;

                                    // 更新数据中的键名
                                    if (this.data[field.field] && this.data[field.field][subField.field]) {
                                        // 保存原始值
                                        const value = this.data[field.field][subField.field];

                                        // 删除旧键
                                        delete this.data[field.field][subField.field];

                                        // 添加新键
                                        subField.field = e.target.value;
                                        this.data[field.field][subField.field] = value;
                                    }
                                });

                                // 添加失去焦点事件处理
                                labelInput.addEventListener('blur', (e) => {
                                    // 获取所有其他输入框的值（排除当前输入框）
                                    const allInputs = switchesContainer.querySelectorAll('input[type="text"]');
                                    const otherValues = Array.from(allInputs)
                                        .filter(input => input !== e.target)
                                        .map(input => input.value);

                                    // 检查当前输入值是否与其它输入框重复
                                    if (otherValues.includes(e.target.value)) {
                                        // 如果重复，标红边框并显示提示文案
                                        e.target.style.border = '2px solid red';
                                        warningText.style.display = 'block';
                                        // 保存状态
                                        inputStates[subField.field] = {
                                            isDuplicate: true,
                                            border: '2px solid red',
                                            warningDisplay: 'block'
                                        };
                                    } else {
                                        // 如果不重复，恢复默认边框并隐藏提示文案
                                        e.target.style.border = '1px solid #ccc';
                                        warningText.style.display = 'none';
                                        // 保存状态
                                        inputStates[subField.field] = {
                                            isDuplicate: false,
                                            border: '1px solid #ccc',
                                            warningDisplay: 'none'
                                        };
                                    }
                                });

                                // 创建滑动开关容器
                                const toggleContainer = document.createElement('div');
                                toggleContainer.className = 'toggle-container';
                                toggleContainer.style.display = 'flex';
                                toggleContainer.style.alignItems = 'center';
                                toggleContainer.style.gap = '5px';

                                // 创建隐藏的input
                                const hiddenInput = document.createElement('input');
                                hiddenInput.type = 'hidden';
                                hiddenInput.name = `${field.field}[${subField.field}]`;
                                hiddenInput.value = currentObjRadioValue[subField.field] || 'off';

                                // 创建滑动开关
                                const toggleSwitch = document.createElement('div');
                                toggleSwitch.className = 'toggle-switch';
                                toggleSwitch.style.position = 'relative';
                                toggleSwitch.style.display = 'inline-block';
                                toggleSwitch.style.width = '40px';
                                toggleSwitch.style.height = '20px';

                                const slider = document.createElement('span');
                                slider.className = 'slider';
                                slider.style.position = 'absolute';
                                slider.style.cursor = 'pointer';
                                slider.style.top = '0';
                                slider.style.left = '0';
                                slider.style.right = '0';
                                slider.style.bottom = '0';
                                slider.style.backgroundColor = hiddenInput.value === 'on' ? '#2196F3' : '#ccc';
                                slider.style.transition = '.4s';
                                slider.style.borderRadius = '34px';

                                const sliderBefore = document.createElement('span');
                                sliderBefore.style.position = 'absolute';
                                sliderBefore.style.content = '';
                                sliderBefore.style.height = '14px';
                                sliderBefore.style.width = '14px';
                                sliderBefore.style.left = '3px';
                                sliderBefore.style.bottom = '3px';
                                sliderBefore.style.backgroundColor = 'white';
                                sliderBefore.style.transition = '.4s';
                                sliderBefore.style.borderRadius = '50%';
                                sliderBefore.style.transform = hiddenInput.value === 'on' ? 'translateX(20px)' : 'translateX(0px)';

                                slider.appendChild(sliderBefore);
                                toggleSwitch.appendChild(slider);

                                // 点击事件处理
                                toggleSwitch.addEventListener('click', () => {
                                    const isOn = hiddenInput.value === 'off';
                                    hiddenInput.value = isOn ? 'on' : 'off';
                                    slider.style.backgroundColor = isOn ? '#2196F3' : '#ccc';
                                    sliderBefore.style.transform = isOn ? 'translateX(20px)' : 'translateX(0px)';

                                    // 更新数据
                                    if (!this.data[field.field]) {
                                        this.data[field.field] = {};
                                    }
                                    this.data[field.field][subField.field] = hiddenInput.value;
                                });

                                toggleContainer.appendChild(toggleSwitch);
                                toggleContainer.appendChild(hiddenInput);

                                // 创建删除按钮
                                const removeBtn = document.createElement('button');
                                removeBtn.textContent = '×';
                                removeBtn.className = 'remove-option-btn';
                                removeBtn.style.background = '#ff4757';
                                removeBtn.style.border = 'none';
                                removeBtn.style.color = 'white';
                                removeBtn.style.cursor = 'pointer';
                                removeBtn.style.fontSize = '16px';
                                removeBtn.style.fontWeight = 'bold';
                                removeBtn.style.padding = '2px 8px';
                                removeBtn.style.borderRadius = '50%';
                                removeBtn.style.display = 'flex';
                                removeBtn.style.alignItems = 'center';
                                removeBtn.style.justifyContent = 'center';
                                removeBtn.style.minWidth = '24px';
                                removeBtn.style.height = '24px';
                                removeBtn.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';
                                removeBtn.style.transition = 'all 0.3s ease';

                                // 添加悬停效果
                                removeBtn.addEventListener('mouseenter', () => {
                                    removeBtn.style.background = '#ff2e43';
                                    removeBtn.style.boxShadow = '0 4px 8px rgba(0,0,0,0.15)';
                                    removeBtn.style.transform = 'translateY(-1px)';
                                });

                                removeBtn.addEventListener('mouseleave', () => {
                                    removeBtn.style.background = '#ff4757';
                                    removeBtn.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';
                                    removeBtn.style.transform = 'translateY(0)';
                                });

                                // 修改删除按钮的click事件处理函数
                                removeBtn.addEventListener('click', () => {
                                    if (objRadioFields.length > 1) { // 至少保留一个选项
                                        objRadioFields.splice(index, 1);

                                        // 从数据中移除
                                        if (this.data[field.field] && this.data[field.field][subField.field]) {
                                            delete this.data[field.field][subField.field];
                                        }

                                        // 重新渲染
                                        renderObjRadioFields();

                                        // 在重新渲染后，重新检查所有输入框的重复值状态
                                        setTimeout(() => {
                                            const allInputs = switchesContainer.querySelectorAll('input[type="text"]');

                                            // 重置所有输入框的状态
                                            allInputs.forEach(input => {
                                                input.style.border = '1px solid #ccc';
                                                const warningText = input.parentNode.querySelector('div[style*="color: red"]');
                                                if (warningText) {
                                                    warningText.style.display = 'none';
                                                }
                                            });

                                            // 检查每个输入框是否与其他输入框重复
                                            allInputs.forEach((input, i) => {
                                                const otherValues = Array.from(allInputs)
                                                    .filter((_, j) => i !== j)
                                                    .map(otherInput => otherInput.value);

                                                if (otherValues.includes(input.value)) {
                                                    // 如果重复，标红边框并显示提示文案
                                                    input.style.border = '2px solid red';
                                                    const warningText = input.parentNode.querySelector('div[style*="color: red"]');
                                                    if (warningText) {
                                                        warningText.style.display = 'block';
                                                    }
                                                }
                                            });
                                        }, 0);
                                    } else {
                                        alert('至少需要保留一个选项!');
                                    }
                                });

                                switchWrapper.appendChild(labelInput);
                                switchWrapper.appendChild(warningText); // 添加提示文案元素
                                switchWrapper.appendChild(toggleContainer);
                                switchWrapper.appendChild(removeBtn);

                                switchesContainer.appendChild(switchWrapper);

                                // 恢复输入框的状态
                                if (inputStates[subField.field]) {
                                    labelInput.style.border = inputStates[subField.field].border;
                                    warningText.style.display = inputStates[subField.field].warningDisplay;
                                }
                            });
                        };

                        // 初始渲染
                        renderObjRadioFields();

                        // 创建添加按钮容器
                        const objRadioAddButtonContainer = document.createElement('div');
                        objRadioAddButtonContainer.style.marginTop = '15px';
                        objRadioAddButtonContainer.style.display = 'flex';
                        objRadioAddButtonContainer.style.justifyContent = 'flex-start';

                        const objRadioAddButton = document.createElement('button');
                        objRadioAddButton.textContent = '+ 添加';
                        objRadioAddButton.className = 'add-option-btn';
                        objRadioAddButton.style.padding = '8px 16px';
                        objRadioAddButton.style.backgroundColor = '#2563EB';
                        objRadioAddButton.style.color = 'white';
                        objRadioAddButton.style.border = 'none';
                        objRadioAddButton.style.borderRadius = '6px';
                        objRadioAddButton.style.cursor = 'pointer';
                        objRadioAddButton.style.fontSize = '14px';
                        objRadioAddButton.style.fontWeight = '500';
                        objRadioAddButton.style.display = 'flex';
                        objRadioAddButton.style.alignItems = 'center';
                        objRadioAddButton.style.gap = '5px';
                        objRadioAddButton.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';
                        objRadioAddButton.style.transition = 'all 0.3s ease';
                        objRadioAddButton.style.marginLeft = 'auto'; // 添加这行实现右对齐

                        // 添加悬停效果
                        objRadioAddButton.addEventListener('mouseenter', () => {
                            objRadioAddButton.style.backgroundColor = '#1D4ED8';
                            objRadioAddButton.style.boxShadow = '0 4px 8px rgba(0,0,0,0.15)';
                            objRadioAddButton.style.transform = 'translateY(-1px)';
                        });

                        objRadioAddButton.addEventListener('mouseleave', () => {
                            objRadioAddButton.style.backgroundColor = '#2563EB';
                            objRadioAddButton.style.boxShadow = '0 2px 4px rgba(0,0,0,0.1)';
                            objRadioAddButton.style.transform = 'translateY(0)';
                        });

                        // 修改添加按钮的click事件处理函数
                        objRadioAddButton.addEventListener('click', () => {
                            // 生成唯一的默认字段名（使用时间戳）
                            const newKey = `选项${Date.now()}`;

                            // 检查是否已存在（理论上不会重复）
                            if (!objRadioFields.some(f => f.field === newKey)) {
                                // 在添加新选项前，先检查新值是否与现有值重复
                                const allCurrentInputs = switchesContainer.querySelectorAll('input[type="text"]');
                                const currentValues = Array.from(allCurrentInputs).map(input => input.value);
                                const newLabel = '';

                                objRadioFields.push({
                                    'field': newKey,
                                    'label': newLabel
                                });

                                // 更新数据
                                if (!this.data[field.field]) {
                                    this.data[field.field] = {};
                                }
                                this.data[field.field][newKey] = 'on';

                                // 重新渲染
                                renderObjRadioFields();

                                // 在重新渲染后，检查所有输入框的重复值
                                setTimeout(() => {
                                    const allInputs = switchesContainer.querySelectorAll('input[type="text"]');

                                    // 先收集所有值，再进行重复检查
                                    const values = Array.from(allInputs).map(input => input.value);
                                    const valueCounts = {};

                                    // 统计每个值出现的次数
                                    values.forEach(value => {
                                        valueCounts[value] = (valueCounts[value] || 0) + 1;
                                    });

                                    // 更新所有输入框的状态
                                    allInputs.forEach(input => {
                                        const warningText = input.parentNode.querySelector('div[style*="color: red"]');
                                        if (valueCounts[input.value] > 1) {
                                            // 如果重复，标红边框并显示提示文案
                                            input.style.border = '2px solid red';
                                            if (warningText) {
                                                warningText.style.display = 'block';
                                            }
                                        } else {
                                            // 如果不重复，恢复默认边框和隐藏提示文案
                                            input.style.border = '1px solid #ccc';
                                            if (warningText) {
                                                warningText.style.display = 'none';
                                            }
                                        }
                                    });
                                }, 0);
                            }
                        });

                        objRadioAddButtonContainer.appendChild(objRadioAddButton);

                        // 将滑动开关容器和添加按钮容器按正确顺序添加到objRadioContainer
                        objRadioContainer.appendChild(switchesContainer);
                        objRadioContainer.appendChild(objRadioAddButtonContainer);

                        inputEl = objRadioContainer;
                        break;
                    
                      

   case 'assembly':
    // 检测是否为移动设备
    const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
    // 创建对象容器
    
    const assemblyObjectContainer = document.createElement('div');
    assemblyObjectContainer.className = 'object-container';
    assemblyObjectContainer.style.marginTop = '10px';
    assemblyObjectContainer.style.padding = '10px';
    assemblyObjectContainer.style.border = '1px solid #e0e0e0';
    assemblyObjectContainer.style.borderRadius = '4px';
    assemblyObjectContainer.style.backgroundColor = '#f9f9f9';
    
    // 创建标题
    const assemblyTitle = document.createElement('div');
    assemblyTitle.className = 'object-title';
    assemblyTitle.style.marginBottom = '10px';
    assemblyTitle.style.fontWeight = 'bold';
    assemblyTitle.textContent = field.label || 'Assembly Object';
    assemblyObjectContainer.appendChild(assemblyTitle);
    
    // 创建对象列表容器
    const assembliesContainer = document.createElement('div');
    assembliesContainer.className = 'objects-container';
    assemblyObjectContainer.appendChild(assembliesContainer);
    
    // 获取当前对象值，确保只包含key包含'总成'的对象
    let currentAssemblies = this.getNestedValue(this.data, field.field) || {};
    
    // 使用field.object_fields代替硬编码的assemblyFields，这样会使用mochat.js中配置的标签
    const assemblyFields = field.object_fields || [
        { field: '分辨率', input_type: 'select', options: field.options || [], label: '分辨率' },
        { field: '屏', input_type: 'select', options: field.options || [], label: '屏' },
        { field: 'TP', input_type: 'select', options: field.options || [], label: 'TP' }
    ];
                                                                         
    // 创建单个对象项的函数
    const createAssemblyItem = (index, item) => {
        const assemblyItem = document.createElement('div');
        assemblyItem.className = 'object-item';
        
        // 设置为inline布局，使分辨率、屏、TP在一行显示
        assemblyItem.style.display = 'flex';
        assemblyItem.style.flexDirection = 'row';
        assemblyItem.style.alignItems = 'center';
        assemblyItem.style.gap = '10px';
        assemblyItem.style.marginBottom = '10px';
        assemblyItem.style.padding = '8px';
        assemblyItem.style.border = '1px solid #ddd';
        assemblyItem.style.borderRadius = '4px';
        
        // 创建嵌套对象头部
        const nestedHeader = document.createElement('div');
        nestedHeader.className = 'nested-object-header';
        nestedHeader.style.display = 'flex';
        nestedHeader.style.alignItems = 'center';
        nestedHeader.style.gap = '5px';
        nestedHeader.style.flexShrink = '0';
        
        // 键输入框
        const keyInput = document.createElement('input');
        keyInput.type = 'text';
        keyInput.value = item.key || `总成${index + 1}`;
        keyInput.style.padding = '6px 10px';
        keyInput.style.border = '1px solid #ddd';
        keyInput.style.borderRadius = '4px';
        keyInput.style.width = '60px';
        
        // 如果不是PC端或不可编辑，禁用键输入
        if (isMobile || !field.editable) {
            keyInput.disabled = true;
            keyInput.style.backgroundColor = '#f5f5f5';
        } else {
            // 键输入框事件处理
            keyInput.addEventListener('change', () => {
                updateAssemblyValue();
            });
        }
        
        nestedHeader.appendChild(keyInput);
        
        // 添加类型切换图标（仅在PC端和可编辑时显示）
        if (field.editable) {
            // 这里应该只放类型切换图标的代码，而不是添加按钮的代码
        }
        
        assemblyItem.appendChild(nestedHeader);
        
        // 渲染键值对
        assemblyFields.forEach((subField, fieldIndex) => {
            // 在非第一个字段前添加分隔小点
            if (fieldIndex > 0) {
                const separator = document.createElement('span');
                separator.textContent = '';
                separator.style.margin = '0 2px'; // 减小字段间间距
                separator.style.color = '#666';
                separator.style.fontSize = '16px';
                assemblyItem.appendChild(separator);
            }

            const formGroup = document.createElement('div');
            formGroup.className = 'form-group';
            formGroup.style.display = 'flex';
            formGroup.style.alignItems = 'center';
            formGroup.style.gap = '1px';
            formGroup.style.flex = '1 1 auto'; // 修改flex属性，使元素能够灵活收缩和扩展
            formGroup.style.minWidth = '0';
            
            const label = document.createElement('label');
            label.textContent = subField.label || subField.field;
            label.style.marginRight = '2px'; // 从5px改为2px，减少右边距
            label.style.whiteSpace = 'nowrap';
            label.style.minWidth = '0'; // 从30px改为0，移除最小宽度限制
            label.style.flexShrink = '0'; // 添加flexShrink确保标签不会被压缩
            
            const subCurrentValue = item[subField.field] || '';
            const subFieldPath = `${field.field}.${item.key || `总成${index + 1}`}.${subField.field}`;
            
            // 创建选择框和自定义输入框容器
            const selectContainer = document.createElement('div');
            selectContainer.style.display = 'flex';
            selectContainer.style.alignItems = 'center';
            
            // 创建选择框
            const selectEl = document.createElement('select');
            selectEl.setAttribute('data-field', subField.field);
            selectEl.style.padding = '6px 10px';
            selectEl.style.border = '1px solid #ddd';
            selectEl.style.borderRadius = '4px';
            selectEl.style.width = '100px';
            
            // 添加选项
            if (subField.options && subField.options.length > 0) {
                subField.options.forEach(option => {
                    const optionEl = document.createElement('option');
                    optionEl.value = option.value || option;
                    optionEl.textContent = option.label || option.value || option;
                    selectEl.appendChild(optionEl);
                });
            }
            
            // 添加"自定义"选项
            const customOption = document.createElement('option');
            customOption.value = '自定义';
            customOption.textContent = '自定义';
            selectEl.appendChild(customOption);
            
            // 设置当前值
            selectEl.value = subCurrentValue;
            
            // 添加：检查是否有匹配的选项，如果没有则动态创建一个新选项
            /* if (subCurrentValue && subCurrentValue !== '自定义' && !Array.from(selectEl.options).some(option => option.value === subCurrentValue)) {
                const newOption = document.createElement('option');
                newOption.value = subCurrentValue;
                newOption.textContent = subCurrentValue;
                newOption.selected = true;
                selectEl.appendChild(newOption);
            } */
            
            // 创建自定义输入框
            const customInput = document.createElement('input');
            customInput.type = 'text';
            customInput.style.display = subCurrentValue === '自定义' ? 'block' : 'none';
            customInput.style.marginLeft = '2px'; // 从5px减小到2px，减少与选择框的间距
            customInput.style.padding = '6px 8px'; // 稍微减小内边距
            customInput.style.border = '1px solid #ddd';
            customInput.style.borderRadius = '4px';
            customInput.style.width = '80px'; // 从100px减小到80px，节省空间
            customInput.setAttribute('data-field', `${subField.field}_custom`);
            
            // 分辨率字段特殊处理
            if (subField.field === '分辨率') {
                // 添加change事件监听器
                selectEl.addEventListener('change', async (e) => {
                    handleResolutionChange(e, item, index);
                });
                
                // 自定义输入框事件监听器
                customInput.addEventListener('input', (e) => {
                    handleResolutionCustomInput(e, item, index);
                });
            } else {
                // 其他字段的change事件处理
                selectEl.addEventListener('change', (e) => {
                    const selectedValue = e.target.value;
                    
                    this.setNestedValue(this.data, subFieldPath, selectedValue);
                    updateAssemblyValue();
                    
                    // 显示或隐藏自定义输入框
                    customInput.style.display = selectedValue === '自定义' ? 'block' : 'none';
                });
            }
            
            // 将选择框和自定义输入框添加到容器中
            selectContainer.appendChild(selectEl);
            selectContainer.appendChild(customInput);
            
            formGroup.appendChild(label);
            formGroup.appendChild(selectContainer);
            assemblyItem.appendChild(formGroup);
        });
        
        // 添加删除按钮（始终显示，移除field.editable检查）
        const removeBtn = document.createElement('button');
        removeBtn.className = 'remove-object-btn';
        // 前3项显示"清空"，保留项
        if (index < 3) {
            removeBtn.textContent = '清空';
            removeBtn.style.background = '#3b82f6'; // 蓝色背景表示清空操作
        } else {
            removeBtn.textContent = '删除';
            removeBtn.style.background = '#ff4757'; // 红色背景表示删除操作
        }
        removeBtn.style.color = 'white';
        removeBtn.style.border = 'none';
        removeBtn.style.padding = '4px 8px';
        removeBtn.style.fontSize = '14px';
        removeBtn.style.borderRadius = '4px';
        removeBtn.style.cursor = 'pointer';
        removeBtn.style.flexShrink = '0';
        
        removeBtn.addEventListener('click', () => {
            // 确保至少保留一个总成项
            const totalItems = assembliesContainer.querySelectorAll('.object-item').length;
            if (totalItems <= 1) {
                alert('至少需要保留一个总成项');
                return;
            }
            
            if (index < 3) {
                // 清空操作：将对象的值设置为空
                const selects = assemblyItem.querySelectorAll('select');
                selects.forEach(select => {
                    select.value = '';
                });
                
                const customInputs = assemblyItem.querySelectorAll('input[type="text"][data-field$="_custom"]');
                customInputs.forEach(input => {
                    input.value = '';
                    input.style.display = 'none';
                });
            } else {
                // 删除操作：移除对象项
                assemblyItem.remove();
                
                // 重新排序编号
                const items = assembliesContainer.querySelectorAll('.object-item');
                items.forEach((item, newIndex) => {
                    const keyInput = item.querySelector('input[type="text"]');
                    // 如果是数字编号的总成，则重新编号
                    if (keyInput.value && keyInput.value.match(/^总成\d+$/)) {
                        keyInput.value = `总成${newIndex + 1}`;
                    }
                    
                    // 更新删除按钮状态
                    const btn = item.querySelector('.remove-object-btn');
                    if (btn) {
                        if (newIndex < 3) {
                            btn.textContent = '清空';
                            btn.style.background = '#3b82f6';
                        } else {
                            btn.textContent = '删除';
                            btn.style.background = '#ff4757';
                        }
                    }
                });
            }
            updateAssemblyValue();
        });
        
        assemblyItem.appendChild(removeBtn);
        
        return assemblyItem;
    };

    // 处理分辨率变更的函数
const handleResolutionChange = async (event, item, index) => {
    const selectedValue = event.target.value;
    const arrayFieldPath = `${field.field}.${item.key || `总成${index + 1}`}`;
    const resolutionFieldPath = `${arrayFieldPath}.分辨率`;
    
    this.setNestedValue(this.data, resolutionFieldPath, selectedValue);
    updateAssemblyValue();
    
    // 显示或隐藏自定义输入框
    const customInput = event.target.nextElementSibling;
    if (selectedValue === '自定义') {
        customInput.style.display = 'block';
    } else {
        customInput.style.display = 'none';
    }
    
    // 无论选择什么值，都更新屏和TP选项
    if (selectedValue === '自定义') {
        // 设置屏和TP为"自定义"
        const screenFieldPath = `${arrayFieldPath}.屏`;
        const tpFieldPath = `${arrayFieldPath}.TP`;
        
        this.setNestedValue(this.data, screenFieldPath, '自定义');
        this.setNestedValue(this.data, tpFieldPath, '自定义');
        
        // 更新对应的DOM元素
        const assemblyItem = event.target.closest('.object-item');
        
        // 更新屏选择框
        const screenSelect = assemblyItem.querySelector(`select[data-field="屏"]`);
        if (screenSelect) {
            // 检查是否已有"自定义"选项
            let customOption = screenSelect.querySelector('option[value="自定义"]');
            if (!customOption) {
                customOption = document.createElement('option');
                customOption.value = '自定义';
                customOption.textContent = '自定义';
                screenSelect.appendChild(customOption);
            }
            screenSelect.value = '自定义';
            // 触发屏选择框的change事件
            screenSelect.dispatchEvent(new Event('change'));
        }
        
        // 更新TP选择框
        const tpSelect = assemblyItem.querySelector(`select[data-field="TP"]`);
        if (tpSelect) {
            // 检查是否已有"自定义"选项
            let customOption = tpSelect.querySelector('option[value="自定义"]');
            if (!customOption) {
                customOption = document.createElement('option');
                customOption.value = '自定义';
                customOption.textContent = '自定义';
                tpSelect.appendChild(customOption);
            }
            tpSelect.value = '自定义';
            // 触发TP选择框的change事件
            tpSelect.dispatchEvent(new Event('change'));
        }
    } else {
        // 调用getAssemblyByResolution函数获取数据
        try {
            const assemblyData = await getAssemblyByResolution(selectedValue);
            
            // 更新当前对象中的屏字段
            updateScreenOptions(assemblyData, arrayFieldPath, event.target.closest('.object-item'));
            
            // 更新当前对象中的TP字段
            updateTpOptions(assemblyData, arrayFieldPath, event.target.closest('.object-item'));
        } catch (error) {
            console.error('获取装配数据失败:', error);
            // 即使API调用失败，也为屏和TP设置默认值或清空
            const screenFieldPath = `${arrayFieldPath}.屏`;
            const tpFieldPath = `${arrayFieldPath}.TP`;
            
            // 清空屏和TP的值
            this.setNestedValue(this.data, screenFieldPath, '');
            this.setNestedValue(this.data, tpFieldPath, '');
            
            // 更新对应的DOM元素
            const assemblyItem = event.target.closest('.object-item');
            if (assemblyItem) {
                const screenSelect = assemblyItem.querySelector(`select[data-field="屏"]`);
                const tpSelect = assemblyItem.querySelector(`select[data-field="TP"]`);
                
                if (screenSelect) {
                    screenSelect.value = '';
                    screenSelect.dispatchEvent(new Event('change'));
                }
                
                if (tpSelect) {
                    tpSelect.value = '';
                    tpSelect.dispatchEvent(new Event('change'));
                }
            }
        }
    }
};

    // 处理分辨率自定义输入的函数
    const handleResolutionCustomInput = (event, item, index) => {
        const customValue = event.target.value;
        const subFieldPath = `${field.field}.${item.key || `总成${index + 1}`}.分辨率`;
        // 验证分辨率格式 (例如: 201-240X296, 2.8-240X320)
        const resolutionRegex = /^\d+X\d+$/;
        
        // 查找当前对象项
        const assemblyItem = event.target.closest('.object-item');
        
        if (assemblyItem) {
            // 获取屏和TP文本输入框
            const screenInput = assemblyItem.querySelector('input[data-field="屏_custom"]');
            const tpInput = assemblyItem.querySelector('input[data-field="TP_custom"]');
            
            if (!resolutionRegex.test(customValue)) {
                // 如果格式不正确，设置输入框边框为红色
                event.target.style.borderColor = 'red';
                console.warn(`Invalid resolution format: ${customValue}`);
                
                // 禁用屏文本输入框
                if (screenInput) {
                    screenInput.disabled = true;
                    screenInput.style.backgroundColor = '#f0f0f0';
                }
                
                // 禁用TP文本输入框
                if (tpInput) {
                    tpInput.disabled = true;
                    tpInput.style.backgroundColor = '#f0f0f0';
                }
            } else {
                // 如果格式正确，恢复默认边框颜色
                event.target.style.borderColor = '#ddd';
                
                // 恢复屏文本输入框
                if (screenInput) {
                    screenInput.disabled = false;
                    screenInput.style.backgroundColor = 'white';
                }
                
                // 恢复TP文本输入框
                if (tpInput) {
                    tpInput.disabled = false;
                    tpInput.style.backgroundColor = 'white';
                }
                
                // 更新数据模型
                this.setNestedValue(this.data, subFieldPath, customValue);
                updateAssemblyValue();
            }
        }
    };

    // 更新屏选项的函数
    const updateScreenOptions = (assemblyData, arrayFieldPath, assemblyItem) => {
        if (assemblyData.screenArray && assemblyData.screenArray.length > 0) {
            const screenValue = assemblyData.screenArray[0].screen;
            const screenFieldPath = `${arrayFieldPath}.屏`;
            
            // 获取当前默认值
            const currentScreenValue = this.getNestedValue(this.data, screenFieldPath) || '';
            
            // 只有当前没有值时才设置默认值
            if (!currentScreenValue) {
                this.setNestedValue(this.data, screenFieldPath, screenValue);
            }
            
            // 更新对应的DOM元素
            const screenSelect = assemblyItem.querySelector(`select[data-field="屏"]`);
            if (screenSelect) {
                // 获取当前屏字段的值
                const currentScreenValue = this.getNestedValue(this.data, screenFieldPath) || '';
                
                // 清空现有选项
                screenSelect.innerHTML = '';
                
                // 创建选项数组，确保当前值在其中
                const screenOptions = assemblyData.screenArray.map(item => item.screen);
                if (currentScreenValue && !screenOptions.includes(currentScreenValue) && currentScreenValue !== '自定义') {
                    screenOptions.unshift(currentScreenValue); // 添加到开头
                }
                
                // 添加"自定义"选项
                if (!screenOptions.includes('自定义')) {
                    screenOptions.push('自定义');
                }
                
                // 添加新的选项
                screenOptions.forEach(value => {
                    const optionEl = document.createElement('option');
                    optionEl.value = value;
                    optionEl.textContent = value;
                    optionEl.selected = value === currentScreenValue;
                    screenSelect.appendChild(optionEl);
                });
                
                // 设置选择框的值，优先使用当前值
                screenSelect.value = currentScreenValue || screenValue;
                // 触发屏选择框的change事件
                screenSelect.dispatchEvent(new Event('change'));
            }
        }
    };

    // 更新TP选项的函数
    const updateTpOptions = (assemblyData, arrayFieldPath, assemblyItem) => {
        if (assemblyData.tpArray && assemblyData.tpArray.length > 0) {
            const tpValue = assemblyData.tpArray[0].tp;
            const tpFieldPath = `${arrayFieldPath}.TP`;
            
            // 获取当前默认值
            const currentTpValue = this.getNestedValue(this.data, tpFieldPath) || '';
            
            // 只有当前没有值时才设置默认值
            if (!currentTpValue) {
                this.setNestedValue(this.data, tpFieldPath, tpValue);
            }
            
            // 更新对应的DOM元素
            const tpSelect = assemblyItem.querySelector(`select[data-field="TP"]`);
            if (tpSelect) {
                // 获取当前TP字段的值
                const currentTpValue = this.getNestedValue(this.data, tpFieldPath) || '';
                
                // 清空现有选项
                tpSelect.innerHTML = '';
                
                // 创建选项数组，确保当前值在其中
                const tpOptions = assemblyData.tpArray.map(item => item.tp);
                if (currentTpValue && !tpOptions.includes(currentTpValue) && currentTpValue !== '自定义') {
                    tpOptions.unshift(currentTpValue); // 添加到开头
                }
                
                // 添加"自定义"选项
                if (!tpOptions.includes('自定义')) {
                    tpOptions.push('自定义');
                }
                
                // 添加新的选项
                tpOptions.forEach(value => {
                    const optionEl = document.createElement('option');
                    optionEl.value = value;
                    optionEl.textContent = value;
                    optionEl.selected = value === currentTpValue;
                    tpSelect.appendChild(optionEl);
                });
                
                // 设置选择框的值，优先使用当前值
                tpSelect.value = currentTpValue || tpValue;
                // 触发TP选择框的change事件
                tpSelect.dispatchEvent(new Event('change'));
            }
        }
    };

    // 更新装配值的函数
    const updateAssemblyValue = () => {
        const items = assembliesContainer.querySelectorAll('.object-item');
        const newObj = {};
        
        items.forEach((item) => {
            const key = item.querySelector('input[type="text"]').value;
            const resolutionSelect = item.querySelector('select[data-field="分辨率"]');
            const screenSelect = item.querySelector('select[data-field="屏"]');
            const tpSelect = item.querySelector('select[data-field="TP"]');
            
            // 检查是否有自定义输入框及其值
            const resolutionCustom = item.querySelector('input[data-field="分辨率_custom"]');
            const screenCustom = item.querySelector('input[data-field="屏_custom"]');
            const tpCustom = item.querySelector('input[data-field="TP_custom"]');
            
            // 获取最终值
            const resolutionValue = resolutionSelect.value === '自定义' && resolutionCustom ? resolutionCustom.value : resolutionSelect.value;
            const screenValue = screenSelect.value === '自定义' && screenCustom ? screenCustom.value : screenSelect.value;
            const tpValue = tpSelect.value === '自定义' && tpCustom ? tpCustom.value : tpSelect.value;
            
            // 保存到对象中
            newObj[key] = {
                '分辨率': resolutionValue,
                '屏': screenValue,
                'TP': tpValue
            };
        });
        
        this.setNestedValue(this.data, field.field, newObj);
    };

    // 初始化渲染
    // 筛选key包含'总成'的对象
    const filteredAssemblies = {};
    Object.keys(currentAssemblies).forEach(key => {
        if (key.includes('总成')) {
            filteredAssemblies[key] = currentAssemblies[key];
        }
    });

    // 如果没有符合条件的对象，创建一个默认的
    if (Object.keys(filteredAssemblies).length === 0) {
        filteredAssemblies['总成1'] = {
            '分辨率': '',
            '屏': '',
            'TP': ''
        };
    }

    // 渲染每个装配项
    let index = 0;
    Object.keys(filteredAssemblies).forEach(key => {
        const item = {
            key: key,
            ...filteredAssemblies[key]
        };
        const assemblyItem = createAssemblyItem(index, item);
        assembliesContainer.appendChild(assemblyItem);
        index++;
    });
    
   // 只保留这一个addBtn声明
    const assemblyAddBtn = document.createElement('button');
    assemblyAddBtn.className = 'add-object-btn';
    assemblyAddBtn.textContent = field.add_button_text || '添加总成';
    assemblyAddBtn.style.background = '#3b82f6';
    assemblyAddBtn.style.color = 'white';
    assemblyAddBtn.style.border = 'none';
    assemblyAddBtn.style.padding = '6px 12px'; // 减小内边距使按钮变小
    assemblyAddBtn.style.fontSize = '14px'; // 减小字体大小
    assemblyAddBtn.style.borderRadius = '4px';
    assemblyAddBtn.style.cursor = 'pointer';
    assemblyAddBtn.style.marginTop = '10px';
    assemblyAddBtn.style.marginLeft = 'auto'; // 自动左边距使其靠右
    assemblyAddBtn.style.display = 'block'; // 确保显示为块级元素
    assemblyAddBtn.style.width = 'auto'; // 自动宽度
    assemblyAddBtn.style.zIndex = '1000'; // 增加
    assemblyAddBtn.style.display = 'block'; // 确保显示
    assemblyAddBtn.style.clear = 'both'; // 清除浮动
    assemblyAddBtn.style.position = 'relative'; // 相对定位确保z-index生效

    // 修改为始终添加点击事件，不再检查field.editable
    assemblyAddBtn.addEventListener('click', async () => {
        // 获取当前总成数量
        const items = assembliesContainer.querySelectorAll('.object-item');
        const newIndex = items.length;
        const newKey = `总成${newIndex + 1}`;
        
        // 初始化新总成对象
        const newObj = {
            key: newKey,
            '分辨率': '',
            '屏': '',
            'TP': ''
        };
        
        // 同步第一个总成的数据（如果存在）
        if (items.length > 0) {
            const firstItem = items[0];
            const firstResolutionSelect = firstItem.querySelector('select[data-field="分辨率"]');
            const firstScreenSelect = firstItem.querySelector('select[data-field="屏"]');
            const firstTpSelect = firstItem.querySelector('select[data-field="TP"]');
            
            // 检查是否有自定义输入框
            const firstResolutionCustom = firstItem.querySelector('input[data-field="分辨率_custom"]');
            const firstScreenCustom = firstItem.querySelector('input[data-field="屏_custom"]');
            const firstTpCustom = firstItem.querySelector('input[data-field="TP_custom"]');
            
            // 获取第一个总成的值
            const firstResolutionValue = firstResolutionSelect.value === '自定义' && firstResolutionCustom ? firstResolutionCustom.value : firstResolutionSelect.value;
            const firstScreenValue = firstScreenSelect.value === '自定义' && firstScreenCustom ? firstScreenCustom.value : firstScreenSelect.value;
            const firstTpValue = firstTpSelect.value === '自定义' && firstTpCustom ? firstTpCustom.value : firstTpSelect.value;
            
            // 同步数据
            newObj['分辨率'] = firstResolutionValue;
            newObj['屏'] = firstScreenValue;
            newObj['TP'] = firstTpValue;
        }
        
        // 创建并添加新的总成项
        const newAssemblyItem = createAssemblyItem(newIndex, newObj);
        assembliesContainer.appendChild(newAssemblyItem);
        
        // 更新数据
        updateAssemblyValue();
    });

    // 无条件将添加按钮添加到container的末尾
    assemblyObjectContainer.appendChild(assemblyAddBtn);


    inputEl = assemblyObjectContainer;
    break;                












                    case 'object':
                        // 创建对象容器
                        const objectContainer = document.createElement('div');
                        objectContainer.className = 'object-form-container';
                        objectContainer.style.margin = '10px 0';

                        // 获取当前对象值或初始化
                        // 将对象转换为包含原始键的对象数组
                        let currentObject = this.getNestedValue(this.data, field.field) || {};
                        // 仅当不是软件配置V3时才转换为数组
                        if (field.field !== '软件配置V3' && typeof currentObject === 'object' && !Array.isArray(currentObject)) {
                            currentObject = Object.entries(currentObject).map(([key, value]) => ({ key, ...value }));
                        }
                        const objectFields = field.object_fields || [];

                        // 检查是否为数组模式（支持多对象）
                        //const isArrayMode = field.array_mode === true || (typeof currentObject === 'object' && !Array.isArray(currentObject));
                        const isArrayMode = field.array_mode === true;
                        if (isArrayMode) {
                            // 数组模式 - 支持多个对象
                            let currentArray = Array.isArray(currentObject) ? currentObject : {};

                            // 对于软件配置V3，始终保持对象格式
                            if (field.field === '软件配置V3') {
                                // 如果初始数据是数组，转换为对象
                                if (Array.isArray(currentObject)) {
                                    const objData = {};
                                    currentObject.forEach((item, index) => {
                                        const key = item.key || `总成${index + 1}`;
                                        objData[key] = item;
                                    });
                                    currentArray = objData;
                                    this.setNestedValue(this.data, field.field, currentArray);
                                } else {
                                    currentArray = currentObject;
                                }
                            } else if (typeof currentObject === 'object' && !Array.isArray(currentObject)) {
                                currentArray = Object.values(currentObject);
                                this.setNestedValue(this.data, field.field, currentArray);
                            }

                            // 创建数组容器
                            const arrayContainer = document.createElement('div');
                            arrayContainer.className = 'object-array-container';

                            // 创建对象列表容器
                            const objectsContainer = document.createElement('div');
                            objectsContainer.className = 'object-items';
                            objectsContainer.style.width = '100%';
                            objectsContainer.style.boxSizing = 'border-box';
                            arrayContainer.appendChild(objectsContainer);

                            // 存储字段路径
                            const arrayFieldPath = field.field;

                            // 创建单个对象的函数
                            const createObjectItem = (index, objData) => {
                                const objItem = document.createElement('div');
                                objItem.className = 'object-item';
                                // 总成样式调整
                                objItem.style.border = '1px solid #e0e0e0';
                                //objItem.style.borderLeft = '5px solid rgb(209, 196, 197)';
                                objItem.style.borderRadius = '4px';
                                objItem.style.padding = '15px 10px 15px 15px';
                                objItem.style.marginBottom = '15px';
                                objItem.style.position = 'relative';
                                objItem.style.width = '100%';
                                objItem.style.boxSizing = 'border-box';
                                objItem.style.backgroundColor = 'white';
                                objItem.style.display = 'flex';
                                objItem.style.flexDirection = 'column';
                                objItem.style.boxShadow = '0 1px 3px rgba(0,0,0,0.1)';
                                // 添加媒体查询适配移动设备
                                objItem.style.minWidth = '100%'; // 设置最小宽度，避免在极小屏幕上过于拥挤

                                // 对象标题
                                const header = document.createElement('div');
                                header.style.fontWeight = 'bold';
                                //header.style.marginBottom = '20px';
                                //header.style.padding = '10px 0';
                                header.className = 'nested-object-header';
                                header.style.display = 'flex';
                                header.style.justifyContent = 'space-between';
                                header.style.alignItems = 'center';
                                header.style.gap = '15px'; // 减小间距以适应小屏幕
                                header.style.flexWrap = 'nowrap';
                                header.style.overflow = 'hidden';
                                header.style.minWidth = '280px'; // 与objItem的minWidth匹配
                                header.style.width = '100%';
                                header.style.boxSizing = 'border-box';
                                header.style.paddingRight = '0';

                                // 创建可编辑的标题输入框
                                const keyInput = document.createElement('input');
                                keyInput.type = 'text';
                                keyInput.value = objData.key || '';
                                keyInput.style.border = 'none';
                                keyInput.style.background = 'transparent';
                                keyInput.style.fontWeight = 'bold';
                                keyInput.style.fontSize = '16px';
                                //keyInput.style.minWidth = '0';
                                keyInput.style.flexGrow = '1';
                                //keyInput.style.minWidth = '120px'; // 减小最小宽度以适应小屏幕
                                keyInput.style.boxSizing = 'border-box';
                                // 移除max-width限制，使用flex布局自然分配空间
                                // keyInput.style.maxWidth = 'calc(100% - 100px)'
                                // 移除nowrap以允许文本换行节省空间
                                // keyInput.style.whiteSpace = 'nowrap';
                                keyInput.style.overflow = 'hidden';
                                keyInput.style.textOverflow = 'ellipsis';
                                keyInput.style.boxSizing = 'border-box';
                                keyInput.style.padding = '4px 5px';
                                // 移除重复的padding样式
                                keyInput.style.borderBottom = '2px solid transparent';
                                keyInput.style.transition = 'border-color 0.2s';

                                // 聚焦时显示边框
                                keyInput.addEventListener('focus', () => {
                                    keyInput.style.borderBottom = '2px solid #3b82f6';
                                });

                                // 失焦时保存修改
                                keyInput.addEventListener('blur', () => {
                                    keyInput.style.borderBottom = '2px solid transparent';
                                    const newKey = keyInput.value.trim();
                                    if (newKey && newKey !== objData.key) {
                                        // 更新对象key
                                        objData.key = newKey;
                                        updateArrayValue();
                                    } else if (!newKey) {
                                        // 确保key不为空
                                        keyInput.value = objData.key;
                                    }
                                });

                                header.appendChild(keyInput);

                                // 删除按钮
                                const removeBtn = document.createElement('button');
                                removeBtn.className = 'remove-object-btn';
                                // 修改按钮文本和样式
                                if (index < 3) {
                                    removeBtn.textContent = '清空';
                                    removeBtn.style.background = '#3b82f6'; // 蓝色背景表示清空操作
                                } else {
                                    removeBtn.textContent = '删除';
                                    removeBtn.style.background = '#ff4757'; // 红色背景表示删除操作
                                }
                                // 移除marginLeft，使用header���gap控制间距
                                // removeBtn.style.marginLeft = '5px';
                                removeBtn.style.flexShrink = '0';
                                // 移除margin-left:auto，使用header的space-between控制对齐
                                // removeBtn.style.marginLeft = 'auto';
                                removeBtn.style.background = '#ff4757';
                                removeBtn.style.color = 'white';
                                removeBtn.style.border = 'none';
                                removeBtn.style.padding = '4px 8px';
                                removeBtn.style.fontSize = '16px';
                                removeBtn.style.flexShrink = '0';
                                removeBtn.style.borderRadius = '4px';
                                removeBtn.style.cursor = 'pointer';
                                removeBtn.style.fontSize = '14px';
                                removeBtn.style.fontWeight = 'bold';
                                removeBtn.style.margin = '0';
                                removeBtn.style.marginBottom = '12px';



                                removeBtn.addEventListener('click', () => {
                                    if (index < 3) {
                                        // 清空操作：将对象的值设置为空
                                        Object.keys(objData).forEach(key => {
                                            if (key !== 'key') { // 保留key字段
                                                objData[key] = '';
                                            }
                                        });
                                        // 更新UI以反映清空后的值
                                        const inputs = objItem.querySelectorAll('input, select');
                                        inputs.forEach(input => {
                                            if (input.getAttribute('data-field')) {
                                                input.value = '';
                                            }
                                        });
                                    } else {
                                        // 删除操作：移除对象项
                                        objItem.remove();
                                    }
                                    updateArrayValue();
                                });

                                // 将删除按钮添加到标题容器，实现同一行显示
                                header.appendChild(removeBtn);
                                objItem.appendChild(header);

                                // 渲染对象字段
                                objectFields.forEach((subField) => {
                                    const formGroup = document.createElement('div');
                                    formGroup.className = 'form-group';
                                    formGroup.style.marginBottom = '15px';

                                    const label = document.createElement('label');
                                    label.textContent = subField.label || subField.field;
                                    label.style.display = 'block'; // 改为block显示
                                    label.style.marginBottom = '5px'; // 增加底部间距
                                    label.style.fontWeight = 'bold'; // 加粗标签文本

                                    let inputEl;
                                    //const subFieldPath = `${arrayFieldPath}[${index}].${subField.field}`;
                                    const subCurrentValue = objData[subField.field] || '';

                                    switch (subField.input_type) {
                                        case 'text':
                                            inputEl = document.createElement('input');
                                            inputEl.type = 'text';
                                            inputEl.value = subCurrentValue;
                                            inputEl.style.width = '200px'; // 改为100%宽度
                                            inputEl.style.padding = '8px';
                                            inputEl.style.border = '1px solid #ddd';
                                            inputEl.style.borderRadius = '4px';
                                            inputEl.style.boxSizing = 'border-box'; // 确保padding不影响总宽度
                                            inputEl.setAttribute('data-field', subField.field);
                                            inputEl.addEventListener('input', (e) => {
                                                //this.setNestedValue(this.data, subFieldPath, e.target.value);
                                                updateArrayValue();
                                            });
                                            break;

                                        case 'select':
                                            // 创建包含选择框和自定义输入框的容器
                                            const selectContainer = document.createElement('div');
                                            selectContainer.style.display = 'flex';
                                            selectContainer.style.alignItems = 'center';
                                            selectContainer.style.gap = '10px';

                                            inputEl = document.createElement('select');
                                            inputEl.style.width = '200px';
                                            inputEl.style.padding = '8px';
                                            inputEl.style.border = '1px solid #ddd';
                                            inputEl.style.borderRadius = '4px';
                                            inputEl.style.backgroundColor = 'white';
                                            inputEl.setAttribute('data-field', subField.field);

                                            // 检查是否为分辨率、屏或TP字段
                                            const isCustomizableField = ['分辨率', '屏', 'TP'].includes(subField.field);

                                            const options = Array.isArray(subField.options) ? [...subField.options] : [];

                                            // 确保当前值在选项中，即使它不在原始options数组中
                                            if (subCurrentValue && !options.find(option => {
                                                const optionValue = typeof option === 'string' ? option : option.value;
                                                return optionValue === subCurrentValue;
                                            })) {
                                                // 只有当当前值不是"自定义"时才添加
                                                if (subCurrentValue !== '自定义') {
                                                    options.push(subCurrentValue);
                                                }
                                            }

                                            // 如果是可自定义字段，添加"自定义"选项
                                            if (isCustomizableField && !options.find(option => option === '自定义')) {
                                                options.push('自定义');
                                            }


                                            options.forEach(option => {
                                                const optionEl = document.createElement('option');
                                                if (typeof option === 'string') {
                                                    optionEl.value = option;
                                                    optionEl.textContent = option;
                                                } else {
                                                    optionEl.value = option.value;
                                                    optionEl.textContent = option.name || option.label || option.value;
                                                }
                                                optionEl.selected = subCurrentValue === optionEl.value;
                                                inputEl.appendChild(optionEl);
                                            });

                                            // 修正：当分辨率字段为空时，默认选择"自定义"选项
                                            // 不修改subCurrentValue常量，而是直接设置inputEl的值
                                            if (subField.field === '分辨率' && !subCurrentValue) {
                                                inputEl.value = '自定义';
                                            }

                                            // 创建自定义输入框（默认隐藏）
                                            const customInput = document.createElement('input');
                                            customInput.type = 'text';
                                            customInput.style.width = '200px';
                                            customInput.style.padding = '8px';
                                            customInput.style.border = '1px solid #ddd';
                                            customInput.style.borderRadius = '4px';
                                            customInput.style.display = 'none'; // 默认隐藏
                                            customInput.setAttribute('data-field', subField.field + '_custom');

                                            // 修正：检查inputEl.value而不是subCurrentValue
                                            if (inputEl.value === '自定义' || subCurrentValue === '自定义') {
                                                inputEl.value = '自定义';
                                                customInput.style.display = 'inline-block';
                                                customInput.value = subCurrentValue || '';
                                            }

                                            inputEl.addEventListener('change', async (e) => {
                                                const selectedValue = e.target.value;
                                                const subFieldPath = `${arrayFieldPath}.${subField.field}`;

                                                // 如果选择了"自定义"
                                                if (selectedValue === '自定义') {
                                                    customInput.style.display = 'inline-block';
                                                    // 输入框的值即为选择框的值
                                                    this.setNestedValue(this.data, subFieldPath, customInput.value);
                                                    customInput.focus(); // 添加聚焦

                                                    // 特别处理屏和TP字段，当它们选择"自定义"时也显示输入框
                                                    if (subField.field === '屏' || subField.field === 'TP') {
                                                        customInput.style.display = 'inline-block';
                                                        customInput.value = '';
                                                        customInput.focus(); // 添加聚焦
                                                    }
                                                    // 更新数据值为自定义
                                                    this.setNestedValue(this.data, subFieldPath, '');
                                                } else {
                                                    // 隐藏自定义输入框
                                                    customInput.style.display = 'none';
                                                    this.setNestedValue(this.data, subFieldPath, selectedValue);
                                                }

                                                // 检查是否有linked_fields配置
                                                if (subField.linked_fields && subField.linked_fields.length > 0) {
                                                    // 特殊处理分辨率字段
                                                    if (subField.field === '分辨率') {
                                                        // 当分辨率选择"自定义"时，同时设置屏和TP为"自定义"
                                                        if (selectedValue === '自定义') {
                                                            const screenFieldPath = `${arrayFieldPath}.屏`;
                                                            this.setNestedValue(this.data, screenFieldPath, '自定义');

                                                            const tpFieldPath = `${arrayFieldPath}.TP`;
                                                            this.setNestedValue(this.data, tpFieldPath, '自定义');

                                                            // 更新对应的DOM元素
                                                            const screenSelect = inputEl.closest('.object-item').querySelector(`select[data-field="屏"]`);
                                                            if (screenSelect) {
                                                                // 检查是否已有"自定义"选项，如果没有则添加
                                                                let customOption = screenSelect.querySelector('option[value="自定义"]');
                                                                if (!customOption) {
                                                                    customOption = document.createElement('option');
                                                                    customOption.value = '自定义';
                                                                    customOption.textContent = '自定义';
                                                                    screenSelect.appendChild(customOption);
                                                                }
                                                                screenSelect.value = '自定义';
                                                                // 触发屏选择框的change事件
                                                                screenSelect.dispatchEvent(new Event('change'));
                                                            }

                                                            const tpSelect = inputEl.closest('.object-item').querySelector(`select[data-field="TP"]`);
                                                            if (tpSelect) {
                                                                // 检查是否已有"自定义"选项，如果没有则添加
                                                                let customOption = tpSelect.querySelector('option[value="自定义"]');
                                                                if (!customOption) {
                                                                    customOption = document.createElement('option');
                                                                    customOption.value = '自定义';
                                                                    customOption.textContent = '自定义';
                                                                    tpSelect.appendChild(customOption);
                                                                }
                                                                tpSelect.value = '自定义';
                                                                // 触发TP选择框的change事件
                                                                tpSelect.dispatchEvent(new Event('change'));
                                                            }

                                                            // 新增：同步更新其他所有总成的分辨率值
                                                            // 获取所有object-item元素
                                                           /*  const allObjectItems = document.querySelectorAll('.object-item');
                                                            allObjectItems.forEach((item, index) => {
                                                                // 跳过当前对象
                                                                if (item === inputEl.closest('.object-item')) return;

                                                                // 更新其他对象的分辨率字段
                                                                const otherResolutionSelect = item.querySelector(`select[data-field="分辨率"]`);
                                                                if (otherResolutionSelect) {
                                                                    otherResolutionSelect.value = selectedValue;

                                                                    // 新增：处理自定义输入框的显示
                                                                    if (selectedValue === '自定义') {
                                                                        // 找到对应的自定义输入框并显示
                                                                        const customInput = otherResolutionSelect.closest('div').querySelector('input[type="text"]');
                                                                        if (customInput) {
                                                                            customInput.style.display = 'block';
                                                                            // 同步自定义输入框的值
                                                                            customInput.value = customInput.value || '';
                                                                        }
                                                                    }

                                                                    // 更新数据模型
                                                                    // 注意：这里需要根据实际的数据结构来确定正确的路径
                                                                    // 假设arrayFieldPath是类似"软件配置V3"的路径
                                                                    // 需要获取对应项的键名
                                                                    const itemKey = Object.keys(this.getNestedValue(this.data, field.field))[index];
                                                                    if (itemKey) {
                                                                        const resolutionFieldPath = `${field.field}.${itemKey}.分辨率`;
                                                                        this.setNestedValue(this.data, resolutionFieldPath, selectedValue);
                                                                    }
                                                                }
                                                            }); */
                                                        } else {
                                                            // 调用getAssemblyByResolution函数获取数据
                                                            try {
                                                                const assemblyData = await getAssemblyByResolution(selectedValue);

                                                                // 更新当前对象中的屏字段
                                                                if (assemblyData.screenArray && assemblyData.screenArray.length > 0) {
                                                                    const screenValue = assemblyData.screenArray[0].screen;
                                                                    const screenFieldPath = `${arrayFieldPath}.屏`;
                                                                    this.setNestedValue(this.data, screenFieldPath, screenValue);

                                                                    // 更新对应的DOM元素
                                                                    const screenSelect = inputEl.closest('.object-item').querySelector(`select[data-field="屏"]`);
                                                                    if (screenSelect) {
                                                                        // 获取当前屏字段的值
                                                                        const currentScreenValue = this.getNestedValue(this.data, screenFieldPath) || '';

                                                                        // 清空现有选项
                                                                        screenSelect.innerHTML = '';

                                                                        // 创建选项数组，确保当前值在其中
                                                                        const screenOptions = assemblyData.screenArray.map(item => item.screen);
                                                                        if (currentScreenValue && !screenOptions.includes(currentScreenValue) && currentScreenValue !== '自定义') {
                                                                            screenOptions.push(currentScreenValue);
                                                                        }

                                                                        // 如果是可自定义字段，添加"自定义"选项
                                                                        if (!screenOptions.includes('自定义')) {
                                                                            screenOptions.push('自定义');
                                                                        }

                                                                        // 添加新的选项
                                                                        screenOptions.forEach(value => {
                                                                            const optionEl = document.createElement('option');
                                                                            optionEl.value = value;
                                                                            optionEl.textContent = value;
                                                                            screenSelect.appendChild(optionEl);
                                                                        });

                                                                        // 设置选择框的值
                                                                        screenSelect.value = currentScreenValue;
                                                                        // 触发屏选择框的change事件
                                                                        screenSelect.dispatchEvent(new Event('change'));

                                                                    }
                                                                }

                                                                // 更新当前对象中的TP字段
                                                                if (assemblyData.tpArray && assemblyData.tpArray.length > 0) {
                                                                    const tpValue = assemblyData.tpArray[0].tp;
                                                                    const tpFieldPath = `${arrayFieldPath}.TP`;
                                                                    this.setNestedValue(this.data, tpFieldPath, tpValue);

                                                                    // 更新对应的DOM元素
                                                                    const tpSelect = inputEl.closest('.object-item').querySelector(`select[data-field="TP"]`);
                                                                    if (tpSelect) {
                                                                        // 获取当前TP字段的值
                                                                        const currentTpValue = this.getNestedValue(this.data, tpFieldPath) || '';

                                                                        // 清空现有选项
                                                                        tpSelect.innerHTML = '';

                                                                        // 创建选项数组，确保当前值在其中
                                                                        const tpOptions = assemblyData.tpArray.map(item => item.tp);
                                                                        if (currentTpValue && !tpOptions.includes(currentTpValue) && currentTpValue !== '自定义') {
                                                                            tpOptions.push(currentTpValue);
                                                                        }

                                                                        // 如果是可自定义字段，添加"自定义"选项
                                                                        if (!tpOptions.includes('自定义')) {
                                                                            tpOptions.push('自定义');
                                                                        }

                                                                        // 添加新的选项
                                                                        tpOptions.forEach(value => {
                                                                            const optionEl = document.createElement('option');
                                                                            optionEl.value = value;
                                                                            optionEl.textContent = value;
                                                                            tpSelect.appendChild(optionEl);
                                                                        });

                                                                        // 设置选择框的值
                                                                        tpSelect.value = currentTpValue;
                                                                        // 触发TP选择框的change事件
                                                                        tpSelect.dispatchEvent(new Event('change'));

                                                                    }
                                                                }

                                                                // 新增：同步更新其他所有总成的分辨率值
                                                                // 获取所有object-item元素
                                                                const allObjectItems = document.querySelectorAll('.object-item');
                                                                allObjectItems.forEach((item, index) => {
                                                                    // 跳过当前对象
                                                                    if (item === inputEl.closest('.object-item')) return;

                                                                    // 更新其他对象的分辨率字段
                                                                    /* const otherResolutionSelect = item.querySelector(`select[data-field="分辨率"]`);
                                                                    if (otherResolutionSelect) {
                                                                        otherResolutionSelect.value = selectedValue;

                                                                        // 更新数据模型
                                                                        const itemKey = Object.keys(this.getNestedValue(this.data, field.field))[index];
                                                                        if (itemKey) {
                                                                            const resolutionFieldPath = `${field.field}.${itemKey}.分辨率`;
                                                                            this.setNestedValue(this.data, resolutionFieldPath, selectedValue);
                                                                        }
                                                                    } */

                                                                    // 同步屏字段选项和值
                                                                    /* const otherScreenSelect = item.querySelector(`select[data-field="屏"]`);
                                                                    if (otherScreenSelect && assemblyData.screenArray) {
                                                                        // 清空现有选项
                                                                        otherScreenSelect.innerHTML = '';
                                                                        
                                                                        // 创建新的选项列表
                                                                        const screenOptions = assemblyData.screenArray.map(item => item.screen);
                                                                        // 确保当前值在选项中
                                                                        const currentScreenValue = this.getNestedValue(this.data, `${field.field}.${Object.keys(this.getNestedValue(this.data, field.field))[index]}.屏`) || '';
                                                                        if (currentScreenValue && !screenOptions.includes(currentScreenValue) && currentScreenValue !== '自定义') {
                                                                            screenOptions.push(currentScreenValue);
                                                                        }
                                                                        
                                                                        // 添加"自定义"选项
                                                                        if (!screenOptions.includes('自定义')) {
                                                                            screenOptions.push('自定义');
                                                                        }
                                                                        
                                                                        // 添加选项到下拉框
                                                                        screenOptions.forEach(value => {
                                                                            const optionEl = document.createElement('option');
                                                                            optionEl.value = value;
                                                                            optionEl.textContent = value;
                                                                            otherScreenSelect.appendChild(optionEl);
                                                                        });
                                                                        
                                                                        // 设置值并触发change事件
                                                                        otherScreenSelect.value = currentScreenValue;
                                                                        otherScreenSelect.dispatchEvent(new Event('change'));
                                                                    } */

                                                                    // 同步TP字段选项和值
                                                                    /* const otherTpSelect = item.querySelector(`select[data-field="TP"]`);
                                                                    if (otherTpSelect && assemblyData.tpArray) {
                                                                        // 清空现有选项
                                                                        otherTpSelect.innerHTML = '';
                                                                        
                                                                        // 创建新的选项列表
                                                                        const tpOptions = assemblyData.tpArray.map(item => item.tp);
                                                                        // 确保当前值在选项中
                                                                        const currentTpValue = this.getNestedValue(this.data, `${field.field}.${Object.keys(this.getNestedValue(this.data, field.field))[index]}.TP`) || '';
                                                                        if (currentTpValue && !tpOptions.includes(currentTpValue) && currentTpValue !== '自定义') {
                                                                            tpOptions.push(currentTpValue);
                                                                        }
                                                                        
                                                                        // 添加"自定义"选项
                                                                        if (!tpOptions.includes('自定义')) {
                                                                            tpOptions.push('自定义');
                                                                        }
                                                                        
                                                                        // 添加选项到下拉框
                                                                        tpOptions.forEach(value => {
                                                                            const optionEl = document.createElement('option');
                                                                            optionEl.value = value;
                                                                            optionEl.textContent = value;
                                                                            otherTpSelect.appendChild(optionEl);
                                                                        });
                                                                        
                                                                        // 设置值并触发change事件
                                                                        otherTpSelect.value = currentTpValue;
                                                                        otherTpSelect.dispatchEvent(new Event('change'));
                                                                    } */
                                                                });
                                                            } catch (error) {
                                                                console.error('获取装配数据失败:', error);
                                                            }
                                                        }
                                                    }
                                                    // 处理其他linked_fields
                                                    subField.linked_fields.forEach(linkedField => {
                                                        // 如果不是分辨率字段的特殊处理，可以在这里添加通用的联动逻辑
                                                    });
                                                }
                                                updateArrayValue();
                                            });

                                            // 自定义输入框事件监听器
                                            customInput.addEventListener('input', (e) => {
                                                const customValue = e.target.value;
                                                const subFieldPath = `${arrayFieldPath}.${subField.field}`;
                                                // 验证分辨率格式 (例如: 201-240X296, 2.8-240X320)
                                                const resolutionRegex = /^\d+(\.\d+)?-\d+X\d+$/;
                                                if (subField.field === '分辨率' && !resolutionRegex.test(customValue)) {
                                                    // 如果格式不正确，设置输入框边框为红色
                                                    customInput.style.borderColor = 'red';
                                                    console.warn(`Invalid resolution format: ${customValue}`);

                                                    // 查找当前对象项中的屏和TP文本输入框，并将其置灰
                                                    const objectContainer = customInput.closest('.object-item, .object-container');
                                                    if (objectContainer) {
                                                        // 禁用屏文本输入框
                                                        const screenInput = objectContainer.querySelector('input[data-field="屏_custom"]');
                                                        if (screenInput) {
                                                            screenInput.disabled = true;
                                                            screenInput.style.backgroundColor = '#f0f0f0';
                                                        }

                                                        // 禁用TP文本输入框
                                                        const tpInput = objectContainer.querySelector('input[data-field="TP_custom"]');
                                                        if (tpInput) {
                                                            tpInput.disabled = true;
                                                            tpInput.style.backgroundColor = '#f0f0f0';
                                                        }
                                                    }
                                                } else {
                                                    // 如果格式正确，恢复默认边框颜色
                                                    customInput.style.borderColor = '#ddd';

                                                    // 查找当前对象项中的屏和TP文本输入框，并恢复其状态
                                                    const objectItem = customInput.closest('.object-item');
                                                    if (objectItem) {
                                                        // 恢复屏文本输入框
                                                        const screenInput = objectItem.querySelector('input[data-field="屏_custom"]');
                                                        if (screenInput) {
                                                            screenInput.disabled = false;
                                                            screenInput.style.backgroundColor = 'white';
                                                        }

                                                        // 恢复TP文本输入框
                                                        const tpInput = objectItem.querySelector('input[data-field="TP_custom"]');
                                                        if (tpInput) {
                                                            tpInput.disabled = false;
                                                            tpInput.style.backgroundColor = 'white';
                                                        }
                                                    }

                                                    this.setNestedValue(this.data, subFieldPath, customValue);
                                                    updateArrayValue();

                                                    // 同步分辨率值到其他总成
                                                    if (subField.field === '分辨率') {
                                                        const allResolutionInputs = document.querySelectorAll('input[data-field="分辨率_custom"]');
                                                        console.log(allResolutionInputs);
                                                        allResolutionInputs.forEach(input => {
                                                            if (input !== customInput) {
                                                                input.value = customValue;
                                                                // 更新对应的数据模型
                                                                const path = input.closest('.object-item').querySelector('input[type="text"]').value;
                                                                const fieldPath = `${arrayFieldPath}.${path}.分辨率`;
                                                                this.setNestedValue(this.data, fieldPath, customValue);
                                                            }
                                                        });
                                                    }
                                                };
                                            });

                                            // 将选择框和自定义输入框添加到容器中
                                            selectContainer.appendChild(inputEl);
                                            selectContainer.appendChild(customInput);

                                            // 使用容器替换原来的inputEl
                                            inputEl = selectContainer;
                                            break;

                                        default:
                                            inputEl = document.createElement('input');
                                            inputEl.type = 'text';
                                            inputEl.value = subCurrentValue;
                                            inputEl.style.width = '100%';
                                            inputEl.style.padding = '8px';
                                            inputEl.style.border = '1px solid #ddd';
                                            inputEl.style.borderRadius = '4px';
                                            inputEl.setAttribute('data-field', subField.field);
                                            inputEl.addEventListener('input', (e) => {
                                                this.setNestedValue(this.data, subFieldPath, e.target.value);
                                                updateArrayValue();
                                            });
                                    }

                                    formGroup.appendChild(label);
                                    formGroup.appendChild(inputEl);
                                    objItem.appendChild(formGroup);
                                });

                                return objItem;
                            };

                            // 更新数组值的函数
                            const updateArrayValue = () => {
                                const items = objectsContainer.querySelectorAll('.object-item');
                                const newObj = {};  // 创建对象而不是数组

                                items.forEach((item) => {
                                    // 获取key值
                                    const keyInput = item.querySelector('.nested-object-header input[type="text"]');
                                    const key = keyInput ? keyInput.value.trim() : `总成${Object.keys(newObj).length + 1}`;

                                    const obj = {};
                                    objectFields.forEach(subField => {
                                        const fieldName = subField.field;
                                        const inputEl = item.querySelector(`[data-field="${fieldName}"]`);
                                        if (inputEl) {
                                            obj[fieldName] = inputEl.value;
                                        }
                                    });
                                    newObj[key] = obj;  // 使用key作为属性名
                                });

                                // 保存为对象格式
                                this.setNestedValue(this.data, arrayFieldPath, newObj);
                            };

                            // 初始化现有对象
                            let arrayData = currentArray;
                            if (Array.isArray(currentArray)) {
                                // 如果是数组，转换为对象
                                const objData = {};
                                currentArray.forEach((item, index) => {
                                    const key = item.key || `总成${index + 1}`;
                                    objData[key] = item;
                                });
                                arrayData = objData;
                                this.setNestedValue(this.data, field.field, arrayData);
                            }

                            // 遍历对象数据
                            Object.entries(arrayData).forEach(([key, objData]) => {
                                const item = { key, ...objData };
                                const objItem = createObjectItem(Object.keys(arrayData).indexOf(key), item);
                                objectsContainer.appendChild(objItem);
                            });

                            // 创建添加按钮
                        const addBtn = document.createElement('button');
                            addBtn.className = 'add-object-btn';
                            addBtn.textContent = field.add_button_text || '添加对象';
                            addBtn.style.background = '#3b82f6';
                            addBtn.style.color = 'white';
                            addBtn.style.border = 'none';
                            addBtn.style.padding = '8px 6px';
                            addBtn.style.borderRadius = '4px';
                            addBtn.style.cursor = 'pointer';
                            addBtn.style.marginTop = '10px';
                            addBtn.style.float = 'right';

                        addBtn.addEventListener('click', async () => {
                            // 获取当前总成数量
                            const currentKeys = Object.keys(this.getNestedValue(this.data, arrayFieldPath) || []);
                            const newKey = `总成${currentKeys.length + 1}`;

                            // 初始化包含所有必填字段的总成对象
                            const newObj = {
                                key: newKey,
                                '分辨率': '',
                                '屏': '',
                                'TP': ''
                            };

                            // 获取第一个总成的数据并同步到新总成
                            const arrayData = this.getNestedValue(this.data, arrayFieldPath) || {};
                            const firstKey = Object.keys(arrayData)[0];
                            
                            if (firstKey) {
                                const firstAssembly = arrayData[firstKey];
                                newObj['分辨率'] = firstAssembly['分辨率'] || '';
                                newObj['屏'] = firstAssembly['屏'] || '';
                                newObj['TP'] = firstAssembly['TP'] || '';
                                
                                // 如果第一个总成有分辨率值，获取对应的屏和TP选项列表
                                if (firstAssembly['分辨率']) {
                                    try {
                                        // 调用getAssemblyByResolution函数获取数据
                                        const assemblyData = await getAssemblyByResolution(firstAssembly['分辨率']);

                                        
                                        // 将获取到的选项列表保存到新对象中，以便在createObjectItem中使用
                                        newObj['screenOptions'] = assemblyData.screenArray || [];
                                        newObj['tpOptions'] = assemblyData.tpArray || [];
                                    } catch (error) {
                                        console.error('获取装配数据失败:', error);
                                    }
                                }
                            }

                            const newObjItem = createObjectItem(currentKeys.length, newObj);
                            objectsContainer.appendChild(newObjItem);

                            // 更新数据
                            updateArrayValue();
                        });


                            arrayContainer.appendChild(addBtn);
                            inputEl = arrayContainer;
                            formGroup.appendChild(inputEl);

                        } else if (field.object_style === 'keyed' || Object.values(currentObject).some(v => typeof v === 'object')) {
                            // 键值对多对象渲染模式
                            const objectKeys = Object.keys(currentObject);

                            objectKeys.forEach((key) => {
                                const objItem = document.createElement('div');
                                objItem.className = 'object-item';
                                // 总成样式调整
                                objItem.style.border = '1px solid #e0e0e0';
                                objItem.style.borderLeft = '5px solid rgb(209, 196, 197)';
                                objItem.style.borderRadius = '4px';
                                objItem.style.padding = '15px 10px 15px 15px';
                                objItem.style.marginBottom = '15px';
                                objItem.style.position = 'relative';
                                objItem.style.width = '100%';
                                objItem.style.boxSizing = 'border-box';
                                objItem.style.backgroundColor = 'white';
                                objItem.style.display = 'flex';
                                objItem.style.flexDirection = 'column';
                                objItem.style.boxShadow = '0 1px 3px rgba(0,0,0,0.1)';
                                // 修改最小宽度设置，使其更灵活
                                objItem.style.minWidth = '280px'; // 设置一个合理的最小宽度，而不是100%

                                // 对象标题（键名）
                                const keyHeader = document.createElement('div');
                                keyHeader.style.fontWeight = 'bold';
                                keyHeader.style.marginBottom = '15px';
                                keyHeader.style.paddingBottom = '5px';
                                keyHeader.style.borderBottom = '1px solid #f0f0f0';
                                keyHeader.textContent = key;
                                objItem.appendChild(keyHeader);

                                // 渲染对象字段表单
                                objectFields.forEach((subField) => {
                                    const formGroup = document.createElement('div');
                                    formGroup.className = 'form-group';
                                    formGroup.style.marginBottom = '15px';
                                    formGroup.style.display = 'flex'; // 使用flex布局
                                    formGroup.style.flexDirection = 'column'; // 垂直排列

                                    const label = document.createElement('label');
                                    label.textContent = subField.label || subField.field; // 使用name属性作为标签
                                    label.style.display = 'block';
                                    label.style.marginBottom = '5px';

                                    let inputEl;
                                    const subFieldPath = `${field.field}.${key}.${subField.field}`;
                                    const subCurrentValue = this.getNestedValue(this.data, subFieldPath) || '';

                                    // 根据子字段类型渲染输入控件
                                    switch (subField.input_type) {
                                        case 'text':
                                            inputEl = document.createElement('input');
                                            inputEl.type = 'text';
                                            inputEl.value = subCurrentValue;
                                            inputEl.style.width = '100%';
                                            inputEl.style.padding = '8px';
                                            inputEl.style.border = '1px solid #ddd';
                                            inputEl.style.borderRadius = '4px';
                                            // 添加data-field属性
                                            inputEl.setAttribute('data-field', subField.field);
                                            inputEl.addEventListener('input', (e) => {
                                                this.setNestedValue(this.data, subFieldPath, e.target.value);
                                            });
                                            break;

                                        case 'image':
                                            // 使用封装的createImageUploadComponent方法创建图片上传组件
                                            const imageField = {
                                                field: subFieldPath,
                                                // 传递subField的所有配置属性，包括multiple、galleryData等
                                                ...subField
                                            };
                                            console.log('创建图片字段:', subFieldPath, '配置:', imageField);
                                            console.log('字段对象详细信息:', JSON.stringify(imageField, null, 2));
                                            console.log('当前值:', subCurrentValue);
                                            inputEl = this.createImageUploadComponent(imageField, subCurrentValue);
                                            break;

                                        // 替换case 'select'分支的代码为以下内容：
                                        case 'select':
                                            // 创建包含select和自定义输入框的容器
                                            const selectContainer = document.createElement('div');
                                            selectContainer.style.display = 'flex';
                                            selectContainer.style.alignItems = 'center';
                                            selectContainer.style.gap = '10px';

                                            inputEl = document.createElement('select');
                                            inputEl.style.width = '200px';
                                            inputEl.style.padding = '8px';
                                            inputEl.style.border = '1px solid #ddd';
                                            inputEl.style.borderRadius = '4px';
                                            inputEl.style.backgroundColor = 'white';
                                            inputEl.setAttribute('data-field', subField.field);

                                            // 创建自定义输入框
                                            const customInput = document.createElement('input');
                                            customInput.type = 'text';
                                            customInput.style.width = '200px';
                                            customInput.style.padding = '8px';
                                            customInput.style.border = '1px solid #ddd';
                                            customInput.style.borderRadius = '4px';
                                            customInput.style.display = 'none'; // 默认隐藏

                                            let options = Array.isArray(subField.options) ? subField.options : [];

                                            // 特殊处理屏和TP字段
                                            if (subField.field === '屏' && objData.screenOptions) {
                                                // 使用从第一个总成获取的屏选项
                                                options = objData.screenOptions.map(item => typeof item === 'string' ? item : item.screen || item);
                                            } else if (subField.field === 'TP' && objData.tpOptions) {
                                                // 使用从第一个总成获取的TP选项
                                                options = objData.tpOptions.map(item => typeof item === 'string' ? item : item.tp || item);
                                            }

                                            // 添加'自定义'选项
                                            if (!options.includes('自定义')) {
                                                options.push('自定义');
                                            }

                                            // 检查当前值是否为自定义值
                                            let isCustomValue = false;
                                            if (subCurrentValue) {
                                                const foundInOptions = options.some(option => 
                                                    typeof option === 'string' ? option === subCurrentValue : option.value === subCurrentValue
                                                );
                                                
                                                if (!foundInOptions) {
                                                    isCustomValue = true;
                                                }
                                            }

                                            options.forEach(option => {
                                                const optionEl = document.createElement('option');
                                                const optionValue = typeof option === 'string' ? option : option.value || option;
                                                const optionText = typeof option === 'string' ? option : option.name || option.label || option.value || option;
                                                
                                                optionEl.value = optionValue;
                                                optionEl.textContent = optionText;

                                                // 设置选中状态
                                                if (isCustomValue && optionValue === '自定义') {
                                                    optionEl.selected = true;
                                                } else if (!isCustomValue && subCurrentValue === optionValue) {
                                                    optionEl.selected = true;
                                                }

                                                inputEl.appendChild(optionEl);
                                            });

                                            // 如果是自定义值，显示自定义输入框并设置值
                                            if (isCustomValue) {
                                                customInput.value = subCurrentValue;
                                                customInput.style.display = 'block';
                                            }

                                            inputEl.addEventListener('change', async (e) => {
                                                const selectedValue = e.target.value;

                                                // 如果选择'自定义'，显示输入框
                                                if (selectedValue === '__custom__') {
                                                    customInput.style.display = 'block';
                                                    customInput.focus();
                                                    // 特别处理屏和TP字段
                                                    if (subField.field === '屏' || subField.field === 'TP') {
                                                        customInput.style.display = 'block';
                                                        customInput.value = '';
                                                        customInput.focus(); // 添加聚焦
                                                    }
                                                    // 更新数据值为自定义
                                                    const subFieldPath = `${field.field}.${key}.${subField.field}`;
                                                    this.setNestedValue(this.data, subFieldPath, '');
                                                } else {
                                                    customInput.style.display = 'none';
                                                    const subFieldPath = `${field.field}.${key}.${subField.field}`;
                                                    this.setNestedValue(this.data, subFieldPath, selectedValue);

                                                    // 检查是否有linked_fields配置
                                                    if (subField.linked_fields && subField.linked_fields.length > 0) {
                                                        // 特殊处理分辨率字段
                                                        if (subField.field === '分辨率') {
                                                            // 调用getAssemblyByResolution函数获取数据
                                                            try {
                                                                const assemblyData = await getAssemblyByResolution(selectedValue);
                                                                console.log('获取到的装配数据:', assemblyData); // 添加调试日志

                                                                // 更新当前对象中的屏字段
                                                                if (assemblyData.screenArray && assemblyData.screenArray.length > 0) {
                                                                    const screenValue = assemblyData.screenArray[0].screen;
                                                                    const screenFieldPath = `${arrayFieldPath}.屏`;
                                                                    this.setNestedValue(this.data, screenFieldPath, screenValue);
                                                                    console.log('更新屏字段:', screenValue); // 添加调试日志

                                                                    // 更新对应的DOM元素
                                                                    const screenSelect = inputEl.closest('.object-item').querySelector(`select[data-field="屏"]`);
                                                                    if (screenSelect) {
                                                                        // 清空现有选项
                                                                        screenSelect.innerHTML = '';
                                                                        // 添加新的选项
                                                                        assemblyData.screenArray.forEach(item => {
                                                                            const optionEl = document.createElement('option');
                                                                            optionEl.value = item.screen;
                                                                            optionEl.textContent = item.screen;
                                                                            screenSelect.appendChild(optionEl);
                                                                        });
                                                                        screenSelect.value = screenValue;
                                                                        console.log('更新屏DOM元素:', screenValue); // 添加调试日志
                                                                    } else {
                                                                        console.log('未找到屏DOM元素'); // 添加调试日志
                                                                    }
                                                                }

                                                                // 更新当前对象中的TP字段
                                                                if (assemblyData.tpArray && assemblyData.tpArray.length > 0) {
                                                                    const tpValue = assemblyData.tpArray[0].tp;
                                                                    const tpFieldPath = `${arrayFieldPath}.TP`;
                                                                    this.setNestedValue(this.data, tpFieldPath, tpValue);
                                                                    console.log('更新TP字段:', tpValue); // 添加调试日志

                                                                    // 更新对应的DOM元素
                                                                    const tpSelect = inputEl.closest('.object-item').querySelector(`select[data-field="TP"]`);
                                                                    if (tpSelect) {
                                                                        // 清空现有选项
                                                                        tpSelect.innerHTML = '';
                                                                        // 添加新的选项
                                                                        assemblyData.tpArray.forEach(item => {
                                                                            const optionEl = document.createElement('option');
                                                                            optionEl.value = item.tp;
                                                                            optionEl.textContent = item.tp;
                                                                            tpSelect.appendChild(optionEl);
                                                                        });
                                                                        tpSelect.value = tpValue;
                                                                        console.log('更新TPDOM元素:', tpValue); // 添加调试日志
                                                                    } else {
                                                                        console.log('未找到TPDOM元素'); // 添加调试日志
                                                                    }
                                                                }
                                                            } catch (error) {
                                                                console.error('获取装配数据失败:', error);
                                                            }
                                                        }
                                                        // 处理其他linked_fields
                                                        subField.linked_fields.forEach(linkedField => {
                                                            // 如果不是分辨率字段的特殊处理，可以在这里添加通用的联动逻辑
                                                        });
                                                    }
                                                    updateArrayValue();
                                                }
                                            });

                                            // 自定义输入框的事件监听
                                            customInput.addEventListener('input', (e) => {
                                            

                                                const customValue = e.target.value;
                                                const subFieldPath = `${arrayFieldPath}.${subField.field}`;
                                                this.setNestedValue(this.data, subFieldPath, customValue);
                                                updateArrayValue();
                                            });

                                            // 将select和自定义输入框添加到容器中
                                            selectContainer.appendChild(inputEl);
                                            selectContainer.appendChild(customInput);

                                            // 使用容器作为inputEl
                                            inputEl = selectContainer;
                                            break;

                                        case 'radio':
                                            const radioGroup = document.createElement('div');
                                            radioGroup.style.display = 'flex';
                                            radioGroup.style.flexDirection = 'column';
                                            radioGroup.style.gap = '10px';
                                            radioGroup.style.padding = '5px 0';

                                            subField.options.forEach(option => {
                                                const radioContainer = document.createElement('div');
                                                radioContainer.style.display = 'flex';
                                                radioContainer.style.alignItems = 'center';
                                                radioContainer.style.gap = '10px';

                                                // 创建滑动开关容器
                                                const toggleSwitch = document.createElement('div');
                                                toggleSwitch.className = 'toggle-switch';
                                                toggleSwitch.style.position = 'relative';
                                                toggleSwitch.style.display = 'inline-block';
                                                toggleSwitch.style.width = '50px';
                                                toggleSwitch.style.height = '24px';

                                                // 创建隐藏的checkbox
                                                const checkbox = document.createElement('input');
                                                checkbox.type = 'checkbox';
                                                checkbox.className = 'toggle-input';
                                                checkbox.checked = subCurrentValue === option.value;
                                                checkbox.style.opacity = '0';
                                                checkbox.style.width = '0';
                                                checkbox.style.height = '0';

                                                // 创建滑动条
                                                const slider = document.createElement('span');
                                                slider.className = 'slider';
                                                slider.style.position = 'absolute';
                                                slider.style.cursor = 'pointer';
                                                slider.style.top = '0';
                                                slider.style.left = '0';
                                                slider.style.right = '0';
                                                slider.style.bottom = '0';
                                                slider.style.backgroundColor = '#ccc';
                                                slider.style.transition = '.4s';
                                                slider.style.borderRadius = '34px';

                                                // 滑动按钮
                                                const sliderBefore = document.createElement('span');
                                                sliderBefore.style.position = 'absolute';
                                                sliderBefore.style.content = '';
                                                sliderBefore.style.height = '16px';
                                                sliderBefore.style.width = '16px';
                                                sliderBefore.style.left = '4px';
                                                sliderBefore.style.bottom = '4px';
                                                sliderBefore.style.backgroundColor = 'white';
                                                sliderBefore.style.transition = '.4s';
                                                sliderBefore.style.borderRadius = '50%';

                                                toggleSwitch.appendChild(checkbox);
                                                toggleSwitch.appendChild(slider);
                                                slider.appendChild(sliderBefore);

                                                // 添加标签文本
                                                const labelText = document.createElement('span');
                                                labelText.textContent = option.label || option.value;
                                                labelText.style.fontSize = '14px';

                                                // 点击事件处理
                                                toggleSwitch.addEventListener('click', () => {
                                                    // 取消其他选项的选中状态
                                                    radioGroup.querySelectorAll('.toggle-input').forEach(input => {
                                                        input.checked = false;
                                                        input.parentElement.querySelector('.slider').style.backgroundColor = '#ccc';
                                                        input.parentElement.querySelector('.slider span').style.transform = 'translateX(0px)';
                                                    });

                                                    // 设置当前选项为选中状态
                                                    checkbox.checked = true;
                                                    slider.style.backgroundColor = '#2196F3';
                                                    sliderBefore.style.transform = 'translateX(26px)';

                                                    // 更新数据
                                                    this.setNestedValue(this.data, subFieldPath, option.value);
                                                });

                                                // 初始化样式
                                                if (checkbox.checked) {
                                                    slider.style.backgroundColor = '#2196F3';
                                                    sliderBefore.style.transform = 'translateX(26px)';
                                                }

                                                radioContainer.appendChild(toggleSwitch);
                                                radioContainer.appendChild(labelText);
                                                radioGroup.appendChild(radioContainer);
                                            });
                                            inputEl = radioGroup;
                                            break;

                                        default:
                                            inputEl = document.createElement('input');
                                            inputEl.type = 'text';
                                            inputEl.value = subCurrentValue;
                                            inputEl.style.width = '100%';
                                            inputEl.style.padding = '8px';
                                            inputEl.style.border = '1px solid #ddd';
                                            inputEl.style.borderRadius = '4px';
                                            inputEl.addEventListener('input', (e) => {
                                                this.setNestedValue(this.data, subFieldPath, e.target.value);
                                            });
                                    }

                                    formGroup.appendChild(label);
                                    formGroup.appendChild(inputEl);
                                    objItem.appendChild(formGroup);
                                });

                                objectContainer.appendChild(objItem);
                            });
                        } else {
                            // 新增非数组模式处理逻辑
                            const objectContainer = document.createElement('div');
                            objectContainer.className = 'object-container';
                            objectContainer.style.width = '100%';
                            objectContainer.style.boxSizing = 'border-box';

                            // 获取当前对象值
                            let currentObjectValue = this.getNestedValue(this.data, field.field) || {};

                            // 动态获取object_fields
                            let dynamicObjectFields = field.object_fields || [];

                            // 如果没有明确指定object_fields，但field有default_value，则从default_value生成
                            if (dynamicObjectFields.length === 0 && field.default_value && typeof field.default_value === 'object') {
                                dynamicObjectFields = Object.keys(field.default_value).map(key => ({
                                    'field': key,
                                    'label': key,
                                    'input_type': 'text'
                                }));
                                console.log('从default_value生成dynamicObjectFields:', dynamicObjectFields);
                            }

                            // 如果提供了generateObjectFields函数，则调用它
                            if (typeof field.generateObjectFields === 'function') {
                                dynamicObjectFields = field.generateObjectFields();
                                console.log('从generateObjectFields生成dynamicObjectFields:', dynamicObjectFields);
                            }

                            // 如果没有明确指定object_fields，但currentObjectValue有属性，则自动生成
                            if (dynamicObjectFields.length === 0 && typeof currentObjectValue === 'object') {
                                dynamicObjectFields = Object.keys(currentObjectValue).map(key => ({
                                    'field': key,
                                    'label': key,
                                    'input_type': 'text' // 默认类型，可以根据需要修改
                                }));
                                console.log('从currentObjectValue生成dynamicObjectFields:', dynamicObjectFields);
                            }

                            // 渲染对象字段
                            console.log('开始渲染对象字段，共', dynamicObjectFields.length, '个字段');
                            dynamicObjectFields.forEach((subField, index) => {
                                console.log('渲染第', index + 1, '个字段:', subField);
                                const formGroup = document.createElement('div');
                                formGroup.className = 'form-group';
                                formGroup.style.marginBottom = '15px';
                                formGroup.style.border = '1px solid #f0f0f0'; // 添加边框以便调试
                                formGroup.style.padding = '10px';

                                const label = document.createElement('label');
                                label.textContent = subField.label || subField.field;
                                label.style.display = 'block';
                                label.style.marginBottom = '5px';
                                label.style.fontWeight = 'bold';

                                let inputEl;
                                const subFieldPath = `${field.field}.${subField.field}`;
                                // 优先从field.default_value获取默认值
                                let subCurrentValue = this.getNestedValue(this.data, subFieldPath);
                                if (subCurrentValue === undefined || subCurrentValue === null) {
                                    subCurrentValue = field.default_value && field.default_value[subField.field] || '';
                                }
                                console.log('字段', subField.field, '的值:', subCurrentValue);

                                // 强制设置为text类型，确保显示为文本输入框
                                subField.input_type = 'text';

                                switch (subField.input_type) {
                                    case 'text':
                                        inputEl = document.createElement('input');
                                        inputEl.type = 'text';
                                        inputEl.value = subCurrentValue;
                                        inputEl.style.width = '100%';
                                        inputEl.style.padding = '8px';
                                        inputEl.style.border = '1px solid #ddd';
                                        inputEl.style.borderRadius = '4px';
                                        inputEl.style.boxSizing = 'border-box';
                                        // 添加data-field属性
                                        inputEl.setAttribute('data-field', subField.field);
                                        inputEl.addEventListener('input', (e) => {
                                            this.setNestedValue(this.data, subFieldPath, e.target.value);
                                        });
                                        break;
                                    // 其他类型的处理...
                                }

                                formGroup.appendChild(label);
                                formGroup.appendChild(inputEl);
                                objectContainer.appendChild(formGroup);
                            });

                            // 确保objectContainer被添加到DOM中
                            inputEl = objectContainer;
                            console.log('对象容器已创建，包含', objectContainer.children.length, '个子元素');

                            inputEl = objectContainer;
                        }

                        inputEl = objectContainer;
                        break;
                    case 'image':
                        // 创建图片字段配置，使用dataPath
                        const imageFieldConfig = {
                            ...field,
                            field: dataPath
                        };
                        inputEl = this.createImageUploadComponent(imageFieldConfig, currentValue);
                        break;


                    case 'file':
                        // 创建文件字段配置，使用dataPath
                        const fileFieldConfig = {
                            ...field,
                            field: dataPath
                        };
                        inputEl = this.createFileUploadComponent(fileFieldConfig, currentValue);
                        break;

                    case 'inputarray':
                        // 创建数组控件容器
                        const arrayContainer = document.createElement('div');
                        arrayContainer.className = 'input-array-container';

                        // 创建数组项容器
                        const itemsContainer = document.createElement('div');
                        itemsContainer.className = 'array-items';
                        arrayContainer.appendChild(itemsContainer);

                        // 获取当前数组值，默认为空数组
                        const arrayValue = Array.isArray(currentValue) ? currentValue : [];

                        // 存储数组字段路径
                        const arrayFieldPath = field.field;

                        // 检查重复值并更新样式
                        const checkDuplicateValues = () => {
                            const items = itemsContainer.querySelectorAll('.array-item');
                            const values = [];

                            // 收集所有值
                            items.forEach((item) => {
                                const inputEl = item.querySelector('input[type="text"]');
                                if (inputEl) {
                                    values.push(inputEl.value);
                                }
                            });

                            // 统计每个值出现的次数
                            const valueCounts = {};
                            values.forEach(value => {
                                if (value) { // 只统计非空值
                                    valueCounts[value] = (valueCounts[value] || 0) + 1;
                                }
                            });

                            // 更新样式
                            items.forEach((item) => {
                                const inputEl = item.querySelector('input[type="text"]');

                                if (inputEl) {
                                    // 移除之前可能添加的提示元素
                                    const existingError = item.querySelector('.duplicate-error');
                                    if (existingError) {
                                        existingError.remove();
                                    }

                                    // 检查当前值是否重复
                                    if (inputEl.value && valueCounts[inputEl.value] > 1) {
                                        // 标红边框
                                        inputEl.style.borderColor = '#ff4d4f';
                                        inputEl.style.borderWidth = '2px';

                                        // 添加错误提示
                                        const errorDiv = document.createElement('div');
                                        errorDiv.className = 'duplicate-error';
                                        errorDiv.style.color = '#ff4d4f';
                                        errorDiv.style.fontSize = '12px';
                                        errorDiv.style.marginTop = '5px';
                                        errorDiv.style.marginRight = '10px';
                                        errorDiv.textContent = '存在相同的配置';
                                        item.appendChild(errorDiv);
                                    } else {
                                        // 恢复默认边框
                                        inputEl.style.borderColor = '';
                                        inputEl.style.borderWidth = '';
                                    }
                                }
                            });
                        };

                        // 创建单个数组项的函数 - 移除options相关逻辑
                        const createArrayItem = (index, value) => {
                            const itemContainer = document.createElement('div');
                            itemContainer.className = 'array-item';

                            // 始终创建文本输入框
                            const input = document.createElement('input');
                            input.type = 'text';
                            input.value = value || '';
                            input.placeholder = `请输入第${index + 1}项`;

                            // 在输入事件中检查重复值
                            input.addEventListener('input', () => {
                                updateArrayValueInputArray();
                                setTimeout(() => {
                                    checkDuplicateValues();
                                }, 0);
                            });

                            // 创建删除按钮
                            const removeBtn = document.createElement('button');
                            removeBtn.className = 'remove-btn';
                            removeBtn.textContent = '×';
                            removeBtn.addEventListener('click', () => {
                                itemContainer.remove();
                                updateArrayValueInputArray();
                                // 删除后重新检查重复值
                                setTimeout(() => {
                                    checkDuplicateValues();
                                }, 0);
                            });

                            itemContainer.appendChild(input);
                            itemContainer.appendChild(removeBtn);
                            return itemContainer;
                        };

                        // 更新数组值的函数 - 重命名以避免冲突
                        const updateArrayValueInputArray = () => {
                            const items = itemsContainer.querySelectorAll('.array-item');
                            const newArray = [];
                            items.forEach((item) => {
                                const inputEl = item.querySelector('input[type="text"]');
                                if (inputEl) {
                                    newArray.push(inputEl.value);
                                }
                            });
                            this.setNestedValue(this.data, arrayFieldPath, newArray);

                            // 添加事件触发机制，通知支持语言数组已更新
                            const arrayUpdateEvent = new CustomEvent('arrayUpdated', {
                                detail: {
                                    fieldPath: arrayFieldPath,
                                    newValue: newArray
                                }
                            });
                            document.dispatchEvent(arrayUpdateEvent);
                        };

                        // 初始化现有数组项
                        arrayValue.forEach((value, index) => {
                            const item = createArrayItem(index, value);
                            itemsContainer.appendChild(item);
                        });

                        // 创建添加按钮
                        const addBtn = document.createElement('button');
                        addBtn.className = 'add-btn';
                        addBtn.textContent = '+ 添加';
                        addBtn.addEventListener('click', () => {
                            const newIndex = itemsContainer.children.length;
                            const newItem = createArrayItem(newIndex, '');
                            itemsContainer.appendChild(newItem);

                            // 添加后重新检查重复值
                            setTimeout(() => {
                                checkDuplicateValues();
                            }, 0);
                        });

                        arrayContainer.appendChild(addBtn);

                        // 初始化时检查重复值
                        setTimeout(() => {
                            checkDuplicateValues();
                        }, 0);

                        inputEl = arrayContainer;
                        break;
                        inputEl = document.createElement('input');
                        inputEl.type = 'text';
                        inputEl.value = currentValue;
                        inputEl.addEventListener('input', (e) => {
                            this.setNestedValue(this.data, field.field, e.target.value);
                        });
                }

                formGroup.appendChild(inputEl);
                categoryContent.appendChild(formGroup);
            });

            this.container.appendChild(categorySection);
        });

    }


    // 获取更新后的数据
    getUpdatedData() {
        // 创建一个新对象，避免修改原始数据
        const formattedData = {};

        for (const key in this.data) {
            if (Object.prototype.hasOwnProperty.call(this.data, key)) {
                const value = this.data[key];
                // 处理undefined和null值
                formattedData[key] = (value === undefined || value === null) ? "无" : value;
            }
        }

        // 在返回数据之前，先进行组合字段数据映射
        if (formattedData.组合) {
            console.log('[getUpdatedData] 开始处理组合字段数据映射:', formattedData.组合);
            
            // 处理尺寸屏幕形状组合
            if (formattedData.组合['尺寸屏幕形状组合']) {
                const sizeScreenData = formattedData.组合['尺寸屏幕形状组合'];
                console.log('[getUpdatedData] 从组合字段获取尺寸和屏幕形状数据:', sizeScreenData);
                
                // 确保软件配置V3存在
                if (!formattedData.软件配置V3) {
                    formattedData.软件配置V3 = {};
                }
                
                // 映射尺寸数据
                if (sizeScreenData.尺寸 !== undefined) {
                    formattedData.软件配置V3.尺寸 = sizeScreenData.尺寸;
                    console.log('[getUpdatedData] 已映射尺寸数据:', sizeScreenData.尺寸);
                }
                
                // 映射屏幕形状数据
                if (sizeScreenData.屏幕形状 !== undefined) {
                    formattedData.软件配置V3.屏幕形状 = sizeScreenData.屏幕形状;
                    console.log('[getUpdatedData] 已映射屏幕形状数据:', sizeScreenData.屏幕形状);
                }
            }
            
            // 处理蓝牙音频语言组合
            if (formattedData.组合['蓝牙音频语言组合']) {
                const bluetoothAudioData = formattedData.组合['蓝牙音频语言组合'];
                console.log('[getUpdatedData] 从组合字段获取蓝牙音频数据:', bluetoothAudioData);
                
                // 确保软件配置V1存在
                if (!formattedData.软件配置V1) {
                    formattedData.软件配置V1 = {};
                }
                
                // 映射蓝牙名数据
                if (bluetoothAudioData.蓝牙名 !== undefined) {
                    formattedData.软件配置V1.蓝牙名 = bluetoothAudioData.蓝牙名;
                    console.log('[getUpdatedData] 已映射蓝牙名数据:', bluetoothAudioData.蓝牙名);
                }
                
                // 映射音频名数据
                if (bluetoothAudioData.音频名 !== undefined) {
                    formattedData.软件配置V1.音频名 = bluetoothAudioData.音频名;
                    console.log('[getUpdatedData] 已映射音频名数据:', bluetoothAudioData.音频名);
                }
            }
            
            // 处理基础版本表盘组合
            if (formattedData.组合['基础版本表盘组合']) {
                const baseVersionData = formattedData.组合['基础版本表盘组合'];
                console.log('[getUpdatedData] 从组合字段获取基础版本表盘数据:', baseVersionData);
                
                // 映射基础版本数据
                if (baseVersionData.基础版本 !== undefined) {
                    formattedData.基础版本 = baseVersionData.基础版本;
                    console.log('[getUpdatedData] 已映射基础版本数据:', baseVersionData.基础版本);
                }
                
                // 确保软件配置V5存在
                if (!formattedData.软件配置V5) {
                    formattedData.软件配置V5 = {};
                }
                
                // 映射表盘数据
                if (baseVersionData.表盘 !== undefined) {
                    formattedData.软件配置V5.表盘 = baseVersionData.表盘;
                    console.log('[getUpdatedData] 已映射表盘数据:', baseVersionData.表盘);
                }
            }
            
            console.log('[getUpdatedData] 组合字段数据映射完成');
        }

        // 删除不需要的顶级字段
        delete formattedData.参考附图;
        delete formattedData.开机logo;
        delete formattedData.关机logo;
        console.log('已从提交数据中删除顶级字段: 参考附图, 开机logo, 关机logo');

        return formattedData;
    }

    // 重置表单数据
    resetData() {
        this.data = JSON.parse(JSON.stringify(this.originalData));
        this.renderForm();
    }






    
    // 清理滚动事件监听器
    static cleanupScrollEvents() {
        // 查找layer弹窗容器
        const layerPopup = document.querySelector('.layui-layer-content');
        const scrollToBottomBtn = document.getElementById('scroll-to-bottom');

        // 如果存在滚动到底部按钮，移除点击事件监听器并隐藏
        if (scrollToBottomBtn) {
            if (typeof layui !== 'undefined' && layui.$) {
                layui.$(scrollToBottomBtn).off('click');
            } else if (typeof $ !== 'undefined') {
                $(scrollToBottomBtn).off('click');
            } else {
                // 原生移除事件
                scrollToBottomBtn.replaceWith(scrollToBottomBtn.cloneNode(true));
            }
            scrollToBottomBtn.style.display = 'none';
        }

        // 如果存在layer弹窗，移除滚动事件监听器
        if (layerPopup) {
            if (typeof layui !== 'undefined' && layui.$) {
                layui.$(layerPopup).off('scroll');
            } else if (typeof $ !== 'undefined') {
                $(layerPopup).off('scroll');
            } else {
                // 原生移除事件
                layerPopup.replaceWith(layerPopup.cloneNode(true));
            }
            // 清除弹窗内的滚动条样式
            layerPopup.style.overflow = '';
        }

        // 移除窗口事件监听器
        if (typeof layui !== 'undefined' && layui.$) {
            layui.$(window).off('resize scroll');
            layui.$(document).off('scroll');
        } else if (typeof $ !== 'undefined') {
            $(window).off('resize scroll');
            $(document).off('scroll');
        } else {
            // 原生移除事件
            window.onresize = null;
            window.onscroll = null;
            document.onscroll = null;
        }

        //console.log('已清理所有滚动相关事件监听器和样式');
    }

    /**
 * 创建图片上传组件
 * @param {Object} field - 字段配置对象
 * @param {string|Array} currentValue - 当前值（单选时为字符串，多选时为数组）
 * @returns {HTMLElement} - 图片上传容器元素
 */
createImageUploadComponent(field, currentValue) {
        // 默认单选模式，可通过配置设置为多选
        const isMultiple = field.multiple === true;
        const imageContainer = document.createElement('div');
        imageContainer.className = 'image-upload-container';
        imageContainer.style.display = 'flex';
        imageContainer.style.flexDirection = 'row';
        imageContainer.style.width = '100%';
        imageContainer.style.marginBottom = '15px';
        imageContainer.style.alignItems = 'flex-start';
        imageContainer.style.flexWrap = 'wrap';
        imageContainer.style.gap = '10px';

        


    // 文件上传控件（隐藏）
    const fileInput = document.createElement('input');
    fileInput.type = 'file';
    fileInput.accept = 'image/*';
    fileInput.className = 'image-upload-input';
    fileInput.style.display = 'none';
    // 根据配置设置multiple属性
    if (isMultiple) {
        fileInput.multiple = true;
    }

    // 图片预览区域 - 作为上传按钮的预览容器
    const previewContainer = document.createElement('div');
    previewContainer.className = 'image-preview-container';
    // 核心样式：虚线边框、居中布局
    previewContainer.style.border = '2px dashed #ccc';
    previewContainer.style.borderRadius = '4px';
    previewContainer.style.width = '100px';
    previewContainer.style.height = '100px';
    previewContainer.style.display = 'flex';
    previewContainer.style.flexDirection = 'column';
    previewContainer.style.alignItems = 'center';
    previewContainer.style.justifyContent = 'center';
    previewContainer.style.cursor = 'pointer';
    previewContainer.style.boxSizing = 'border-box';
    previewContainer.style.position = 'relative'; // 添加相对定位，使清空按钮的绝对定位生效

    // 添加中央加号图标
    const plusIcon = document.createElement('div');
    plusIcon.style.fontSize = '45px';
    plusIcon.style.color = '#ccc';
    plusIcon.style.marginBottom = '10px';
    plusIcon.style.lineHeight = '1';
    plusIcon.textContent = '+';
    // 初始状态设置 - 多选模式下始终显示添加按钮
    plusIcon.style.display = (isMultiple || !currentValue) ? 'block' : 'none';

     // 提示文本 - 支持自定义
    const hintText = document.createElement('div');
    hintText.className = 'image-text-placeholder';
    // 使用uploadHint的值，不显示文件数量限制提示
    hintText.textContent = field.uploadHint || '';
    hintText.style.fontSize = '14px';
    hintText.style.color = '#666';
    hintText.style.display = 'none';
    // 添加绝对定位，避免影响加号居中
    hintText.style.position = 'absolute';
    hintText.style.bottom = '10px';
    hintText.style.left = '50%';
    hintText.style.transform = 'translateX(-50%)';
    hintText.style.textAlign = 'center';
    hintText.style.width = '100%';

    // 添加清空按钮
    const clearBtn = document.createElement('button');
    clearBtn.className = 'image-clear-btn';
    // 设置按钮样式为垃圾桶图标
    clearBtn.style.width = '20px';
    clearBtn.style.height = '20px';
    clearBtn.style.position = 'absolute';
    clearBtn.style.padding = '0';
    clearBtn.style.margin = '0';
    clearBtn.style.top = '5px';
    clearBtn.style.right = '5px';
    clearBtn.style.backgroundColor = 'transparent';
    clearBtn.style.backgroundImage = 'url(./assets/images/index/del.png)';
    clearBtn.style.backgroundSize = 'contain';
    clearBtn.style.backgroundRepeat = 'no-repeat';
    clearBtn.style.backgroundPosition = 'center';
    clearBtn.style.border = 'none';
    clearBtn.style.cursor = 'pointer';
    clearBtn.style.display = 'none'; // 初始隐藏
    clearBtn.title = '清空图片';
    
    // 在多选模式下不显示虚线框内的清空按钮
    if (isMultiple) {
        clearBtn.style.display = 'none';
    }

    // 添加默认图库选择按钮
    const galleryBtn = document.createElement('button');
    galleryBtn.className = 'image-gallery-btn';
    galleryBtn.textContent = '默认图库';
    galleryBtn.style.position = 'absolute';
    galleryBtn.style.bottom = '5px';
    galleryBtn.style.left = '5px';
    galleryBtn.style.padding = '2px 5px';
    galleryBtn.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
    galleryBtn.style.color = '#fff';
    galleryBtn.style.border = 'none';
    galleryBtn.style.borderRadius = '3px';
    galleryBtn.style.cursor = 'pointer';
    galleryBtn.style.fontSize = '12px';
    galleryBtn.title = '选择默认图片';
    // 添加下面这行来隐藏按钮
    galleryBtn.style.display = 'none'; // 隐藏默认图库按钮
    previewContainer.appendChild(galleryBtn);

    // 组合预览区域内容
    previewContainer.appendChild(plusIcon);
    previewContainer.appendChild(hintText);
    previewContainer.appendChild(clearBtn);

    // 点击整个预览区域触发文件选择
    previewContainer.addEventListener('click', (e) => {
        // 如果点击的是清空按钮或默认图库按钮，则不触发文件选择
        if (e.target === clearBtn || e.target === galleryBtn) return;

        // 触发默认图库按钮的点击事件，显示图库窗口
        galleryBtn.click();
    });

    // 添加拖拽上传支持
    previewContainer.addEventListener('dragover', (e) => {
        e.preventDefault();
        previewContainer.classList.add('drag-over');
        // 拖拽时改变边框颜色
        previewContainer.style.borderColor = '#3b82f6';
    });

    previewContainer.addEventListener('dragleave', () => {
        previewContainer.classList.remove('drag-over');
        // 离开时恢复边框颜色
        previewContainer.style.borderColor = '#ccc';
    });

    previewContainer.addEventListener('drop', (e) => {
        e.preventDefault();
        previewContainer.classList.remove('drag-over');
        previewContainer.style.borderColor = '#ccc';

        if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
            fileInput.files = e.dataTransfer.files;
            const event = new Event('change', { bubbles: true });
            fileInput.dispatchEvent(event);
        }
    });

    // 加载状态提示
    const loadingEl = document.createElement('div');
    loadingEl.className = 'image-loading';
    loadingEl.style.display = 'none';
    loadingEl.style.alignItems = 'center';
    loadingEl.style.justifyContent = 'center';
    loadingEl.style.flexDirection = 'column';

    const spinner = document.createElement('div');
    spinner.className = 'loading-spinner';
    spinner.style.width = '30px';
    spinner.style.height = '30px';
    spinner.style.border = '3px solid #f3f3f3';
    spinner.style.borderTop = '3px solid #3b82f6';
    spinner.style.borderRadius = '50%';
    spinner.style.animation = 'spin 1s linear infinite';

    loadingEl.appendChild(spinner);
    loadingEl.appendChild(document.createTextNode(' 图片上传中...'));

    // 错误提示
    const errorEl = document.createElement('div');
    errorEl.className = 'image-error';
    errorEl.textContent = '图片加载失败，请重试';
    errorEl.style.color = '#f44336';
    errorEl.style.display = 'none';
    errorEl.style.padding = '8px 12px';
    errorEl.style.fontSize = '14px';
    errorEl.style.backgroundColor = '#ffebee';
    errorEl.style.borderRadius = '4px';
    errorEl.style.marginTop = '8px';
    errorEl.style.width = '180px';
    errorEl.style.boxSizing = 'border-box';
    errorEl.style.textAlign = 'center';
    errorEl.style.position = 'relative';
    errorEl.style.zIndex = '0'; // 确保错误提示在底层

    previewContainer.appendChild(loadingEl);
    // 将错误提示添加到imageContainer而不是previewContainer
    imageContainer.appendChild(previewContainer);
    imageContainer.appendChild(errorEl);

    // 存储预览容器引用
    this.imagePreviews.set(field.field, previewContainer);

    // 处理图片显示 - 增强的初始化逻辑
    console.log('[多图初始化] 字段:', field.field, '当前值:', currentValue, '类型:', typeof currentValue, '是否多选:', isMultiple);
    
    // 更全面的值检查
    const hasValue = currentValue !== null && currentValue !== undefined && currentValue !== '' && 
                     (Array.isArray(currentValue) ? currentValue.length > 0 : true);
    
    console.log('[多图初始化] 是否有值:', hasValue);
    
    if (hasValue) {
        // 将单个图片转换为数组格式以便统一处理
        const images = Array.isArray(currentValue) ? currentValue : [currentValue];
        console.log('[多图初始化调试] 处理后的图片数组:', images);
        
        if (isMultiple) {
            // 多选模式：所有图片都创建独立的容器，保持虚线框用于添加新图片
            console.log('[初始化多图] 创建图片容器:', images.length, '张图片');
            
            // 过滤掉空值，并更新数据中的空值
            const validImages = images.filter(imgSrc => imgSrc && imgSrc.trim() !== '');
            console.log('[初始化多图] 有效图片数量:', validImages.length);
            
            // 如果有效图片数量与原始数组不同，更新数据
            if (validImages.length !== images.length) {
                console.log('[初始化多图] 检测到空值，清理数据中的空值');
                // 检查是否是对象字段中的图片（通过容器上的同步函数）
                if (imageContainer && typeof imageContainer._syncImageData === 'function') {
                    console.log('检测到对象字段图片，使用专用同步逻辑清理空值');
                    imageContainer._syncImageData(validImages);
                } else {
                    // 普通字段的处理
                    this.setNestedValue(this.data, field.field, validImages);
                }
            }
            
            validImages.forEach((imgSrc, index) => {
                console.log(`[初始化多图] 创建第${index + 1}张图片容器:`, imgSrc);
                const imageItemContainer = this.createImageItemContainer(imgSrc, field);
                
                // 紧急修复：立即强制显示容器
                imageItemContainer.style.cssText = `
                    display: block !important;
                    visibility: visible !important;
                    opacity: 1 !important;
                    width: 100px !important;
                    height: 100px !important;
                    border: 1px solid #ddd !important;
                    border-radius: 4px !important;
                    position: relative !important;
                    margin-right: 10px !important;
                    margin-bottom: 10px !important;
                    background-color: #f9f9f9 !important;
                    overflow: hidden !important;
                    z-index: 1000 !important;
                `;
                
                // 强制显示内部图片
                const img = imageItemContainer.querySelector('img');
                if (img) {
                    img.style.cssText = `
                        display: block !important;
                        visibility: visible !important;
                        opacity: 1 !important;
                        width: 100% !important;
                        height: 100% !important;
                        object-fit: cover !important;
                    `;
                }
                
                // 将图片容器插入到虚线框之前
                imageContainer.insertBefore(imageItemContainer, previewContainer);
                
                console.log('[紧急修复] 图片容器已创建并强制显示:', imgSrc);
            });
            
            // 多选模式下虚线框保持可见，用于添加新图片
            hintText.style.display = 'block';
            plusIcon.style.display = 'block';
            
            console.log('[初始化多图] UI容器创建完成，验证同步状态');
            
            // 强制确保所有图片容器可见 - 关键修复
            validImages.forEach((imgSrc, index) => {
                setTimeout(() => {
                    const containers = imageContainer.querySelectorAll('.image-item-container');
                    if (containers[index]) {
                        const container = containers[index];
                        // 强制应用显示样式
                        container.style.display = 'block';
                        container.style.visibility = 'visible';
                        container.style.opacity = '1';
                        container.style.position = 'relative';
                        container.style.zIndex = '100';
                        
                        // 确保图片也可见
                        const img = container.querySelector('img');
                        if (img) {
                            img.style.display = 'block';
                            img.style.visibility = 'visible';
                            img.style.opacity = '1';
                        }
                        
                        console.log(`[强制显示修复] 图片容器${index + 1}已强制设为可见:`, imgSrc);
                    }
                }, index * 10); // 错开时间确保每个容器都被处理
            });
            
            // 在 DOM 更新完成后验证初始化同步状态
            setTimeout(() => {
                this.verifyMultiImageSync(field, imageContainer, '初始化完成后');
                
                // 二次确认显示状态 - 双重保险
                const finalContainers = imageContainer.querySelectorAll('.image-item-container');
                finalContainers.forEach((container, index) => {
                    if (window.getComputedStyle(container).display === 'none') {
                        console.warn(`[显示修复] 检测到隐藏的容器${index + 1}，强制显示`);
                        container.style.display = 'block !important';
                        container.style.visibility = 'visible !important';
                        container.style.opacity = '1 !important';
                    }
                });
                
                // 添加强制显示检查
                this.forceDisplayImageContainers(imageContainer, '初始化后检查');
                
                // 紧急修复：持续监控并修复隐藏容器
                this.startEmergencyDisplayMonitor(imageContainer, field);
            }, 100);
        } else {
            // 单选模式：使用虚线框内显示图片
            const imgSrc = images[0];
            if (imgSrc && imgSrc.trim() !== '') {
                // 隐藏提示文本和加号
                hintText.style.display = 'none';
                plusIcon.style.display = 'none';
                
                // 显示加载状态
                loadingEl.style.display = 'flex';
                
                // 创建预览图片
                this.createPreviewImage(imgSrc, previewContainer, loadingEl, clearBtn, hintText, plusIcon, errorEl, isMultiple);
            }
        }
    } else {
        // 没有图片时确保隐藏
        clearBtn.style.display = 'none';
        console.log('[初始化] 无初始值，显示虚线框');
    }

    // 清空按钮点击事件
    clearBtn.addEventListener('click', () => {
        this.handleClearImage(field, previewContainer, fileInput, clearBtn, hintText, plusIcon, errorEl, isMultiple, imageContainer);
    });

    // 默认图库按钮点击事件
    galleryBtn.addEventListener('click', () => {
        this.handleGalleryClick(field, previewContainer, fileInput, clearBtn, hintText, plusIcon, errorEl, isMultiple, imageContainer);
    });

    // 文件选择后处理
    fileInput.addEventListener('change', (e) => {
        if (e.target.files && e.target.files.length > 0) {
            this.handleFileChange(e.target.files, field, previewContainer, loadingEl, clearBtn, hintText, plusIcon, errorEl, isMultiple, imageContainer);
        }
    });

    // 添加样式
    imageContainer.appendChild(fileInput);
    imageContainer.appendChild(errorEl);
    imageContainer.appendChild(previewContainer);
    
    return imageContainer;
}

// 创建单个图片预览项容器
createImageItemContainer(imgSrc, field = null) {
    console.log('[创建ImageItemContainer] 开始创建:', imgSrc);
    
    // 创建容器
    const container = document.createElement('div');
    container.className = 'image-item-container';
    
    // 使用cssText设置所有样式，确保最高优先级
    container.style.cssText = `
        display: block !important;
        visibility: visible !important;
        opacity: 1 !important;
        width: 100px !important;
        height: 100px !important;
        border: 2px solid #007bff !important;
        border-radius: 6px !important;
        box-sizing: border-box !important;
        position: relative !important;
        margin: 5px !important;
        flex-shrink: 0 !important;
        background-color: #f8f9fa !important;
        overflow: hidden !important;
        z-index: 9999 !important;
        float: left !important;
        box-shadow: 0 2px 4px rgba(0,0,0,0.1) !important;
    `;
    
    // 创建预览图片
    const img = document.createElement('img');
    
    // 标准化图片URL格式 - 关键修复
    let normalizedSrc = imgSrc;
    if (imgSrc && imgSrc.trim() !== '') {
        if (!imgSrc.startsWith('http') && !imgSrc.startsWith('/') && !imgSrc.startsWith('file://')) {
            // 处理Windows路径中的反斜杠
            normalizedSrc = imgSrc.replace(/\\/g, '/'); // 将\替换为/
            console.log('[图片URL标准化] 转换为:', normalizedSrc);
        }
        
        // 更严格的URL处理，移除可能存在的引号
        normalizedSrc = normalizedSrc.replace(/['"]/g, '');
    } else {
        console.warn('[创建ImageItemContainer] 无效的图片URL:', imgSrc);
        // 设置一个默认的占位图，确保容器不会为空
        normalizedSrc = 'data:image/svg+xml;charset=utf-8,%3Csvg xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22 viewBox%3D%220 0 200 200%22%3E%3Cpath fill%3D%22%23eeeeee%22 d%3D%22M0 0h200v200H0z%22%2F%3E%3Ctext fill%3D%22%23aaaaaa%22 font-family%3D%22Arial%22 font-size%3D%2212%22 text-anchor%3D%22middle%22 x%3D%22100%22 y%3D%22100%22 dy%3D%22.3em%22%3E图片缺失%3C%2Ftext%3E%3C%2Fsvg%3E';
    }
    
    img.src = normalizedSrc;
    img.className = 'preview-image';
    
    // 使用cssText设置图片样式，确保最高优先级
    img.style.cssText = `
        width: 100% !important;
        height: 100% !important;
        object-fit: cover !important;
        border-radius: 4px !important;
        display: block !important;
        opacity: 1 !important;
        visibility: visible !important;
        transition: opacity 0.3s ease !important;
    `;
    
    // 添加图片加载状态监听 - 增强版
    img.onload = () => {
        console.log('[图片加载成功]:', normalizedSrc);
        console.log('[图片加载成功] 容器状态检查:', {
            display: window.getComputedStyle(container).display,
            visibility: window.getComputedStyle(container).visibility,
            opacity: window.getComputedStyle(container).opacity
        });
        
        // 加载成功后确保图片可见
        img.style.display = 'block';
        container.style.backgroundColor = '#f9f9f9';
        container.style.display = 'block';
        container.style.opacity = '1';
        container.style.visibility = 'visible';
        
        // 再次确认显示状态
        setTimeout(() => {
            const finalStyle = window.getComputedStyle(container);
            console.log('[图片加载成功] 最终状态:', {
                display: finalStyle.display,
                visibility: finalStyle.visibility,
                opacity: finalStyle.opacity
            });
        }, 100);
    };
    
    img.onerror = (error) => {
        console.error('[图片加载失败]:', normalizedSrc, error);
        // 加载失败时显示错误提示
        container.style.backgroundColor = '#ffebee';
        container.innerHTML = '<div style="display:flex;align-items:center;justify-content:center;width:100%;height:100%;color:#f44336;font-size:12px;">加载失败</div>';
        // 确保错误状态的容器仍然可见
        container.style.display = 'block';
        container.style.opacity = '1';
        container.style.visibility = 'visible';
    };
    
    container.appendChild(img);
    
    // 添加删除按钮
    const delBtn = document.createElement('button');
    delBtn.className = 'image-item-delete-btn';
    delBtn.style.width = '20px';
    delBtn.style.height = '20px';
    delBtn.style.position = 'absolute';
    delBtn.style.padding = '0';
    delBtn.style.margin = '0';
    delBtn.style.top = '5px';
    delBtn.style.right = '5px';
    delBtn.style.backgroundColor = 'transparent';
    delBtn.style.backgroundImage = 'url(./assets/images/index/del.png)';
    delBtn.style.backgroundSize = 'contain';
    delBtn.style.backgroundRepeat = 'no-repeat';
    delBtn.style.backgroundPosition = 'center';
    delBtn.style.border = 'none';
    delBtn.style.cursor = 'pointer';
    delBtn.title = '删除图片';
    container.appendChild(delBtn);
    
    // 保存FormGenerator实例引用以便在事件处理器中使用
    const formGeneratorInstance = this;
    
    // 添加删除按钮点击事件（关键修复）
    delBtn.addEventListener('click', (e) => {
        e.stopPropagation(); // 阻止事件冒泡到图片预览
        
        console.log('删除图片按钮点击:', imgSrc, 'field:', field);
        
        // 获取父级图片容器，检查是否有同步函数
        const imageUploadContainer = container.closest('.image-upload-container');
        
        // 从数据中移除对应的图片，获取更新后的值
        const updatedValue = formGeneratorInstance.removeImageFromData(imgSrc, field);
        
        // 如果是对象字段中的图片，还需要调用同步函数
        if (imageUploadContainer && typeof imageUploadContainer._syncImageData === 'function' && updatedValue !== null) {
            console.log('检测到对象字段图片删除，执行同步逻辑，新值:', updatedValue);
            imageUploadContainer._syncImageData(updatedValue);
        }
        
        // 删除当前容器
        if (container.parentNode) {
            container.parentNode.removeChild(container);
        }
        
        // 对于多选字段，验证同步状态
        if (field && field.multiple && imageUploadContainer) {
            formGeneratorInstance.verifyMultiImageSync(field, imageUploadContainer, '图片删除后');
        }
    });
    
    // 添加图片点击预览功能
    img.style.cursor = 'zoom-in';
    img.addEventListener('click', () => {
        // 创建预览背景遮罩
        const previewOverlay = document.createElement('div');
        previewOverlay.style.position = 'fixed';
        previewOverlay.style.top = '0';
        previewOverlay.style.left = '0';
        previewOverlay.style.width = '100%';
        previewOverlay.style.height = '100%';
        previewOverlay.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
        previewOverlay.style.display = 'flex';
        previewOverlay.style.alignItems = 'center';
        previewOverlay.style.justifyContent = 'center';
        previewOverlay.style.zIndex = '99999999';
        previewOverlay.style.cursor = 'zoom-out';

        // 创建预览图片容器
        const previewBox = document.createElement('div');
        previewBox.style.maxWidth = '90%';
        previewBox.style.maxHeight = '90%';
        previewBox.style.display = 'flex';
        previewBox.style.alignItems = 'center';
        previewBox.style.justifyContent = 'center';

        // 创建预览图片
        const previewImg = document.createElement('img');
        previewImg.src = img.src;
        previewImg.style.maxWidth = '100%';
        previewImg.style.maxHeight = '90vh';
        previewImg.style.objectFit = 'contain';

        // 添加到预览容器
        previewBox.appendChild(previewImg);
        previewOverlay.appendChild(previewBox);
        document.body.appendChild(previewOverlay);

        // 点击遮罩关闭预览
        previewOverlay.addEventListener('click', () => {
            document.body.removeChild(previewOverlay);
        });
    });
    
    return container;
}

// 验证多图同步状态
verifyMultiImageSync(field, imageContainer, context) {
    const currentDataValue = this.getNestedValue(this.data, field.field);
    
    // 添加详细的调试信息
    console.log(`[多图同步验证] ${context} - 字段: ${field.field}`);
    console.log('[调试] 原始数据值:', currentDataValue);
    console.log('[调试] 数据类型:', typeof currentDataValue);
    console.log('[调试] 是否为数组:', Array.isArray(currentDataValue));
    
    // 清理并验证数据 - 增强版路径验证
    const dataArray = Array.isArray(currentDataValue) 
        ? currentDataValue.filter(img => {
            const isValid = img && img.trim() !== '' && (img.startsWith('http') || img.startsWith('/') || img.includes('\\') || img.includes('/'));
            if (!isValid) {
                console.warn(`[多图同步验证] 过滤无效图片URL:`, img, '类型:', typeof img);
            }
            return isValid;
          })
        : [];
    
    // 获取当前UI中的有效图片容器
    const uiContainers = Array.from(imageContainer.querySelectorAll('.image-item-container'))
        .filter(container => {
            const img = container.querySelector('img');
            return img && img.src && img.src.trim() !== '';
        });
    
    console.log('[调试] 过滤后的数据数组长度:', dataArray.length, '数据内容:', dataArray);
    console.log('[调试] 有效UI容器数量:', uiContainers.length);
    
    // 只在真正需要同步时才调用fix方法
    if (dataArray.length !== uiContainers.length) {
        console.log(`[多图同步调整] ${context} - 数组长度不匹配，需要调整`);
        console.log('数据数组:', dataArray);
        console.log('UI容器:', uiContainers.map(c => {
            const img = c.querySelector('img');
            return img ? img.src : 'no-image';
        }));
        
        // 尝试修复同步问题
        this.fixMultiImageSync(field, imageContainer, dataArray);
        
        // 修复后立即检查显示状态
        setTimeout(() => {
            this.forceDisplayImageContainers(imageContainer, `${context}后检查`);
        }, 30);
    } else {
        console.log(`[多图同步正常] ${context} - 数组长度一致`);
        
        // 验证内容是否匹配
        const uiImageSrcs = uiContainers.map(container => {
            const img = container.querySelector('img');
            return img ? img.src : '';
        });
        
        // 检查是否所有图片URL都匹配
        let contentMismatch = false;
        const cleanDataArray = dataArray.map(url => url && url.trim() ? url.trim() : '');
        const cleanUiSrcs = uiImageSrcs.map(url => url && url.trim() ? url.trim() : '');
        
        // 检查数据和UI中的图片是否完全匹配（不考虑顺序）
        const dataSet = new Set(cleanDataArray);
        const uiSet = new Set(cleanUiSrcs);
        
        if (dataSet.size !== uiSet.size || !Array.from(dataSet).every(value => uiSet.has(value))) {
            contentMismatch = true;
        }
        
        if (contentMismatch) {
            console.log(`[多图内容调整] ${context} - 内容不完全匹配，需要重新同步`);
            this.fixMultiImageSync(field, imageContainer, dataArray);
        }
    }
}

// 修复多图同步问题
fixMultiImageSync(field, imageContainer, correctDataArray) {
    console.log('[修复多图同步] 开始修复，正确的数据数组:', correctDataArray);
    
    // 确保imageContainer有正确的flex布局样式
    imageContainer.style.display = 'flex';
    imageContainer.style.flexDirection = 'row';
    imageContainer.style.flexWrap = 'wrap';
    imageContainer.style.gap = '10px';
    imageContainer.style.width = '100%';
    imageContainer.style.marginBottom = '15px';
    imageContainer.style.alignItems = 'flex-start';
    
    // 获取预览容器
    const previewContainer = imageContainer.querySelector('.image-preview-container');
    
    // 恢复previewContainer的正确样式 - 虚线框样式
    previewContainer.style.display = 'flex';
    previewContainer.style.flexDirection = 'column';
    previewContainer.style.alignItems = 'center';
    previewContainer.style.justifyContent = 'center';
    previewContainer.style.border = '2px dashed #ccc';
    previewContainer.style.borderRadius = '4px';
    previewContainer.style.width = '100px';
    previewContainer.style.height = '100px';
    previewContainer.style.cursor = 'pointer';
    previewContainer.style.boxSizing = 'border-box';
    previewContainer.style.position = 'relative';
    
    // 清理并验证图片数据
    const validImages = Array.isArray(correctDataArray) 
        ? correctDataArray.filter(img => img && img.trim() !== '') 
        : (correctDataArray ? [correctDataArray] : []);
    
    // 清理并标准化URL（移除反引号和前后空格）
    const cleanValidImages = validImages.map(imgUrl => 
        imgUrl ? imgUrl.replace(/[`']/g, '').trim() : ''
    ).filter(url => url !== '');
    
    // 移除所有现有的图片容器
    const existingContainers = imageContainer.querySelectorAll('.image-item-container');
    existingContainers.forEach(container => {
        imageContainer.removeChild(container);
    });
    
    // 重新创建所有有效图片的容器
    cleanValidImages.forEach(imgUrl => {
        try {
            if (imgUrl && imgUrl !== '') {
                // 创建图片容器
                const newContainer = this.createImageItemContainer(imgUrl, field);
                
                // 确保图片容器的样式正确 - 关键修复
                newContainer.style.display = 'block !important';
                newContainer.style.width = '100px';
                newContainer.style.height = '100px';
                newContainer.style.marginRight = '10px';
                newContainer.style.marginBottom = '10px';
                newContainer.style.flexShrink = '0';
                newContainer.style.border = '1px solid #ddd';
                newContainer.style.borderRadius = '4px';
                newContainer.style.boxSizing = 'border-box';
                newContainer.style.position = 'relative';
                newContainer.style.backgroundColor = '#f9f9f9';
                newContainer.style.overflow = 'hidden';
                
                // 强制应用样式并确保图片容器可见 - 重点强化
                newContainer.style.opacity = '1 !important';
                newContainer.style.visibility = 'visible !important';
                newContainer.style.zIndex = '100';
                
                // 确保图片加载完成后容器可见
                const img = newContainer.querySelector('img');
                if (img) {
                    // 立即设置图片样式
                    img.style.display = 'block !important';
                    img.style.visibility = 'visible !important';
                    img.style.opacity = '1 !important';
                    
                    // 加载完成后再次确认
                    img.onload = function() {
                        this.style.display = 'block !important';
                        this.style.visibility = 'visible !important';
                        this.style.opacity = '1 !important';
                        newContainer.style.display = 'block !important';
                        newContainer.style.visibility = 'visible !important';
                        console.log('[修复多图同步] 图片加载完成，强制显示:', imgUrl);
                    };
                    
                    // 处理加载失败情况
                    img.onerror = function() {
                        console.error('[修复多图同步] 图片加载失败，但保持容器可见:', imgUrl);
                        newContainer.style.display = 'block !important';
                        newContainer.style.visibility = 'visible !important';
                        newContainer.style.backgroundColor = '#ffebee';
                    };
                }
                
                // 将图片容器插入到虚线框预览容器之前
                imageContainer.insertBefore(newContainer, previewContainer);
                
                console.log('[修复多图同步] 成功创建图片容器:', imgUrl);
            }
        } catch (error) {
            console.error('[修复多图同步] 创建图片容器失败:', error);
        }
    });
    
    // 确保数据模型与UI保持一致
    this.setNestedValue(this.data, field.field, cleanValidImages);
    
    // 添加强制显示检查来确保所有容器都可见
    setTimeout(() => {
        this.forceDisplayImageContainers(imageContainer, '修复同步后检查');
    }, 20);
    
    // 在DOM更新后再次验证，但避免过度验证
    setTimeout(() => {
        const containerCount = imageContainer.querySelectorAll('.image-item-container').length;
        const validCount = cleanValidImages.length;
        console.log('[修复多图同步] 修复完成，UI容器数量:', containerCount, '有效数据数量:', validCount);
        
        // 只在严重不匹配时才重新验证，避免无限循环
        if (Math.abs(containerCount - validCount) > 2) {
            console.log('[修复多图同步] 容器数量差异较大，重新验证一次');
            // 只验证一次，不再触发自动修复
            const currentDataValue = this.getNestedValue(this.data, field.field);
            const finalDataArray = Array.isArray(currentDataValue) 
                ? currentDataValue.filter(img => img && img.trim() !== '') 
                : [];
            
            const finalUiContainers = Array.from(imageContainer.querySelectorAll('.image-item-container'))
                .filter(container => {
                    const img = container.querySelector('img');
                    return img && img.src && img.src.trim() !== '';
                });
            
            console.log('[修复多图同步] 最终验证 - 数据长度:', finalDataArray.length, 'UI容器长度:', finalUiContainers.length);
        }
    }, 0);
}

// 紧急显示监控器 - 持续检查并修复隐藏的容器
startEmergencyDisplayMonitor(imageContainer, field) {
    // 避免重复监控
    if (imageContainer._displayMonitor) {
        clearInterval(imageContainer._displayMonitor);
    }
    
    let checkCount = 0;
    const maxChecks = 20; // 最多检查20次（1分钟）
    
    imageContainer._displayMonitor = setInterval(() => {
        checkCount++;
        
        const containers = imageContainer.querySelectorAll('.image-item-container');
        let hiddenCount = 0;
        
        containers.forEach((container, index) => {
            const style = window.getComputedStyle(container);
            const isHidden = style.display === 'none' || 
                           style.visibility === 'hidden' || 
                           parseFloat(style.opacity) < 0.1;
            
            if (isHidden) {
                hiddenCount++;
                console.warn(`[紧急监控] 检测到隐藏容器${index + 1}，立即修复`);
                
                // 用最强的方式强制显示
                container.style.cssText = `
                    display: block !important;
                    visibility: visible !important;
                    opacity: 1 !important;
                    width: 100px !important;
                    height: 100px !important;
                    border: 1px solid #ddd !important;
                    border-radius: 4px !important;
                    position: relative !important;
                    margin-right: 10px !important;
                    margin-bottom: 10px !important;
                    background-color: #f9f9f9 !important;
                    z-index: 1000 !important;
                `;
                
                // 修复内部图片
                const img = container.querySelector('img');
                if (img) {
                    img.style.cssText = `
                        display: block !important;
                        visibility: visible !important;
                        opacity: 1 !important;
                        width: 100% !important;
                        height: 100% !important;
                        object-fit: cover !important;
                    `;
                }
            }
        });
        
        if (hiddenCount > 0) {
            console.log(`[紧急监控] 第${checkCount}次检查，修复${hiddenCount}个隐藏容器`);
        }
        
        // 达到最大检查次数或没有隐藏容器时停止监控
        if (checkCount >= maxChecks || (containers.length > 0 && hiddenCount === 0)) {
            clearInterval(imageContainer._displayMonitor);
            imageContainer._displayMonitor = null;
            console.log(`[紧急监控] 监控结束，共检查${checkCount}次`);
        }
    }, 3000); // 每3秒检查一次
}

// 强制显示检查和修复
forceDisplayImageContainers(imageContainer, context = '') {
    try {
        const containers = imageContainer.querySelectorAll('.image-item-container');
        let fixedCount = 0;
        
        containers.forEach((container, index) => {
            const computedStyle = window.getComputedStyle(container);
            const isHidden = computedStyle.display === 'none' || 
                           computedStyle.visibility === 'hidden' || 
                           computedStyle.opacity === '0';
            
            if (isHidden) {
                console.warn(`[强制显示修复] ${context} - 容器${index + 1}被隐藏，强制显示`);
                
                // 使用!important强制覆盖任何隐藏样式
                container.style.setProperty('display', 'block', 'important');
                container.style.setProperty('visibility', 'visible', 'important');
                container.style.setProperty('opacity', '1', 'important');
                container.style.setProperty('position', 'relative', 'important');
                container.style.setProperty('z-index', '100', 'important');
                
                // 同时修复图片
                const img = container.querySelector('img');
                if (img) {
                    img.style.setProperty('display', 'block', 'important');
                    img.style.setProperty('visibility', 'visible', 'important');
                    img.style.setProperty('opacity', '1', 'important');
                }
                
                fixedCount++;
            }
        });
        
        if (fixedCount > 0) {
            console.log(`[强制显示修复] ${context} - 成功修复 ${fixedCount} 个隐藏容器`);
        }
        
        return fixedCount;
    } catch (error) {
        console.error('[强制显示修复] 修复过程出错:', error);
        return 0;
    }
}

// 检查是否为多图字段
isMultipleImageField(field) {
    return field && field.multiple === true;
}

// 从数据中移除指定的图片
removeImageFromData(imgSrc, field = null) {
    console.log('开始移除图片:', imgSrc, 'field:', field && field.field);
    
    // 如果传递了field参数，则优先从指定字段中移除
    if (field && field.field) {
        console.log(`尝试从指定字段 ${field.field} 中移除图片:`, imgSrc);
        const currentValue = this.getNestedValue(this.data, field.field);
        
        if (Array.isArray(currentValue)) {
            const index = currentValue.indexOf(imgSrc);
            if (index > -1) {
                currentValue.splice(index, 1);
                this.setNestedValue(this.data, field.field, currentValue);
                console.log(`成功从字段 ${field.field} 中移除图片:`, imgSrc, '新值:', currentValue);
                return currentValue; // 返回更新后的值
            }
        } else if (currentValue === imgSrc) {
            this.setNestedValue(this.data, field.field, '');
            console.log(`成功从字段 ${field.field} 中移除图片:`, imgSrc, '新值: 空字符串');
            return ''; // 返回空字符串
        }
    }
    
    // 如果指定字段中没有找到或未传递field参数，则执行全局搜索（保持兼容性）
    console.log('在指定字段中未找到图片，执行全局搜索移除');
    const removeFromField = (obj, path = '') => {
        for (const key in obj) {
            const currentPath = path ? `${path}.${key}` : key;
            const value = obj[key];
            
            if (Array.isArray(value)) {
                // 如果是数组，检查是否包含该图片
                const index = value.indexOf(imgSrc);
                if (index > -1) {
                    value.splice(index, 1);
                    console.log(`已从字段 ${currentPath} 中移除图片:`, imgSrc);
                    return true;
                }
            } else if (value === imgSrc) {
                // 如果是单个值，直接清空
                obj[key] = '';
                console.log(`已从字段 ${currentPath} 中移除图片:`, imgSrc);
                return true;
            } else if (typeof value === 'object' && value !== null) {
                // 递归搜索嵌套对象
                if (removeFromField(value, currentPath)) {
                    return true;
                }
            }
        }
        return false;
    };
    
    removeFromField(this.data);
    return null; // 全局搜索不返回特定值
}


createPreviewImage(imgSrc, previewContainer, loadingEl, clearBtn, hintText, plusIcon, errorEl, isMultiple) {
    const img = document.createElement('img');
    img.src = imgSrc;
    img.className = 'preview-image';
    img.style.maxWidth = '100%';
    img.style.maxHeight = '170px';
    img.style.objectFit = 'contain';
    img.onload = () => {
        loadingEl.style.display = 'none';
        previewContainer.appendChild(img);
        // 修改：多图片模式下不显示虚线框右上角的删除图标
        if (!isMultiple) {
            clearBtn.style.display = 'block'; // 显示清空按钮
        }
        hintText.style.display = 'none'; // 隐藏提示文本
        if (!isMultiple) {
            plusIcon.style.display = 'none'; // 单选模式下隐藏加号图标
        }

        // 添加图片点击预览功能
        img.style.cursor = 'zoom-in';
        img.addEventListener('click', () => {
            // 创建预览背景遮罩
            const previewOverlay = document.createElement('div');
            previewOverlay.style.position = 'fixed';
            previewOverlay.style.top = '0';
            previewOverlay.style.left = '0';
            previewOverlay.style.width = '100%';
            previewOverlay.style.height = '100%';
            previewOverlay.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
            previewOverlay.style.display = 'flex';
            previewOverlay.style.alignItems = 'center';
            previewOverlay.style.justifyContent = 'center';
            previewOverlay.style.zIndex = '99999999';
            previewOverlay.style.cursor = 'zoom-out';

            // 创建预览图片容器
            const previewBox = document.createElement('div');
            previewBox.style.maxWidth = '90%';
            previewBox.style.maxHeight = '90%';
            previewBox.style.display = 'flex';
            previewBox.style.alignItems = 'center';
            previewBox.style.justifyContent = 'center';

            // 创建预览图片
            const previewImg = document.createElement('img');
            previewImg.src = img.src;
            previewImg.style.maxWidth = '100%';
            previewImg.style.maxHeight = '90vh';
            previewImg.style.objectFit = 'contain';

            // 添加到预览容器
            previewBox.appendChild(previewImg);
            previewOverlay.appendChild(previewBox);
            document.body.appendChild(previewOverlay);

            // 点击遮罩关闭预览
            previewOverlay.addEventListener('click', () => {
                document.body.removeChild(previewOverlay);
            });
        });
    };
    img.onerror = () => {
        loadingEl.style.display = 'none';
        // 初始化时不显示错误提示
        // errorEl.style.display = 'block';

        // 强制显示+号和提示文本
        hintText.style.display = 'block';
        hintText.style.zIndex = '1'; // 确保在错误提示上方
        plusIcon.style.display = 'block';
        plusIcon.style.zIndex = '1'; // 确保在错误提示上方

        // 确保预览容器的边框样式正确
        previewContainer.style.border = '2px dashed #ccc';
    };
}

// 处理清空图片
handleClearImage(field, previewContainer, fileInput, clearBtn, hintText, plusIcon, errorEl, isMultiple, imageContainer) {
    console.log('清空图片操作:', field.field, '多选模式:', isMultiple);
    
    // 检查是否是对象字段中的图片（通过容器上的同步函数）
    if (imageContainer && typeof imageContainer._syncImageData === 'function') {
        console.log('检测到对象字段图片清空，使用专用同步逻辑');
        imageContainer._syncImageData(isMultiple ? [] : '');
    } else {
        // 普通字段的处理
        this.setNestedValue(this.data, field.field, isMultiple ? [] : '');
    }

    // 移除所有预览图片
    const existingImgs = previewContainer.querySelectorAll('.preview-image');
    existingImgs.forEach(img => previewContainer.removeChild(img));
    
    // 如果是多选模式，移除所有额外的图片项容器
    if (isMultiple) {
        const imageItems = imageContainer.querySelectorAll('.image-item-container');
        imageItems.forEach(item => imageContainer.removeChild(item));
    }

    // 重置文件输入控件
    fileInput.value = '';

    // 隐藏清空按钮
    clearBtn.style.display = 'none';

    // 显示提示文本和加号图标
    hintText.style.display = 'block';
    plusIcon.style.display = 'block';

    // 隐藏错误提示
    errorEl.style.display = 'none';
}

// 处理图库点击
handleGalleryClick(field, previewContainer, fileInput, clearBtn, hintText, plusIcon, errorEl, isMultiple, imageContainer) {
    // 创建遮罩层
    const galleryOverlay = document.createElement('div');
    galleryOverlay.style.position = 'fixed';
    galleryOverlay.style.top = '0';
    galleryOverlay.style.left = '0';
    galleryOverlay.style.width = '100%';
    galleryOverlay.style.height = '100%';
    galleryOverlay.style.backgroundColor = 'rgba(0, 0, 0, 0.5)';
    galleryOverlay.style.display = 'flex';
    galleryOverlay.style.alignItems = 'center';
    galleryOverlay.style.justifyContent = 'center';
    galleryOverlay.style.zIndex = '99999998';

    // 创建图库选择框
    const galleryBox = document.createElement('div');
    galleryBox.style.width = '80%';
    galleryBox.style.maxWidth = '600px';
    galleryBox.style.maxHeight = '80%';
    galleryBox.style.backgroundColor = '#fff';
    galleryBox.style.borderRadius = '8px';
    galleryBox.style.padding = '20px';
    galleryBox.style.boxSizing = 'border-box';
    galleryBox.style.position = 'relative';
    galleryBox.style.overflowY = 'auto';

    // 添加标题
    const title = document.createElement('h3');
    title.textContent = isMultiple ? '选择图片（可多选）' : '选择图片';
    title.style.marginTop = '0';
    galleryBox.appendChild(title);

    // 添加本地上传选项
    const localUploadContainer = document.createElement('div');
    localUploadContainer.style.display = 'inline-flex';
    localUploadContainer.style.alignItems = 'center';
    localUploadContainer.style.padding = '10px 10px'; // 增加内边距
    localUploadContainer.style.border = 'none'; // 移除边框
    localUploadContainer.style.borderRadius = '6px'; // 增加圆角
    localUploadContainer.style.marginBottom = '15px';
    localUploadContainer.style.marginTop = '20px';
    localUploadContainer.style.cursor = 'pointer';
    localUploadContainer.style.backgroundColor = '#1890ff'; // 蓝色背景
    localUploadContainer.style.color = '#ffffff'; // 白色文字
    localUploadContainer.style.fontWeight = '500'; // 中等字体粗细
    localUploadContainer.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)'; // 添加阴影
    localUploadContainer.style.transition = 'all 0.3s ease'; // 添加过渡效果

    // 添加悬停效果
    localUploadContainer.addEventListener('mouseenter', () => {
        localUploadContainer.style.backgroundColor = '#40a9ff'; // 悬停时的颜色
        localUploadContainer.style.boxShadow = '0 4px 8px rgba(0, 0, 0, 0.15)'; // 悬停时的阴影
    });

    localUploadContainer.addEventListener('mouseleave', () => {
        localUploadContainer.style.backgroundColor = '#1890ff'; // 恢复原色
        localUploadContainer.style.boxShadow = '0 2px 4px rgba(0, 0, 0, 0.1)'; // 恢复原阴影
    });

    const localUploadText = document.createElement('div');
    localUploadText.textContent = '+ 本地上传';
    localUploadText.style.color = '#ffffff';
    localUploadText.style.fontSize = '14px'; // 设置字体大小
    localUploadText.style.lineHeight = '20px'; // 设置行高与图标高度一致

    localUploadContainer.appendChild(localUploadText);

    // 添加点击事件触发文件选择
    localUploadContainer.addEventListener('click', () => {
        fileInput.click();
        document.body.removeChild(galleryOverlay);
    });

    galleryBox.appendChild(localUploadContainer);

    // 创建图片网格容器
    const imageGrid = document.createElement('div');
    imageGrid.style.display = 'grid';
    imageGrid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(100px, 1fr))';
    imageGrid.style.gap = '10px';
    imageGrid.style.marginTop = '10px';

    // 多选模式下存储选中的图片
    let selectedImages = [];
    
    // 获取图库数据源，优先使用字段指定的galleryData，否则使用默认的pictureGallery
    // 动态获取最新的图库数据，支持实时更新
    let galleryDataSource;
    if (field.field && (field.field.endsWith('参考附图') || field.field.includes('主菜单风格'))) {
        // 对于参考附图字段或主菜单风格相关字段，优先使用全局的pictureMainMenuStyleGallery
        galleryDataSource = window.pictureMainMenuStyleGallery || field.galleryData || window.pictureGallery || {};
        console.log('使用主菜单风格图库:', galleryDataSource);
    } else {
        // 其他字段使用原有逻辑
        galleryDataSource = field.galleryData || window.pictureGallery || {};
    }
    
    // 遍历图库数据源，添加图片
    Object.keys(galleryDataSource).forEach(groupName => {
        // 添加分组标题
        const groupTitle = document.createElement('h4');
        groupTitle.textContent = groupName;
        groupTitle.style.gridColumn = '1 / -1';
        groupTitle.style.margin = '10px 0 5px';
        imageGrid.appendChild(groupTitle);

        // 添加该分组的图片
        galleryDataSource[groupName].forEach(imageUrl => {
            const imgContainer = document.createElement('div');
            imgContainer.style.position = 'relative';
            imgContainer.style.cursor = 'pointer';
            imgContainer.style.border = '2px solid transparent';
            imgContainer.style.borderRadius = '4px';
            imgContainer.style.transition = 'border-color 0.3s';

            const img = document.createElement('img');
            img.src = imageUrl;
            img.style.width = '100%';
            img.style.height = '100px';
            img.style.objectFit = 'cover';
            img.style.borderRadius = '4px';

            imgContainer.appendChild(img);
            imageGrid.appendChild(imgContainer);

            // 添加点击事件
            imgContainer.addEventListener('click', () => {
                if (isMultiple) {
                    // 多选模式
                    const index = selectedImages.indexOf(imageUrl);
                    if (index > -1) {
                        // 取消选中
                        selectedImages.splice(index, 1);
                        imgContainer.style.borderColor = 'transparent';
                        imgContainer.style.backgroundColor = 'transparent';
                    } else {
                        // 选中图片
                        selectedImages.push(imageUrl);
                        imgContainer.style.borderColor = '#3b82f6';
                        imgContainer.style.backgroundColor = 'rgba(59, 130, 246, 0.1)';
                    }
                } else {
                    // 单选模式 - 直接处理
                    this.handleImageSelect(imageUrl, field, previewContainer, clearBtn, hintText, plusIcon, errorEl, isMultiple, imageContainer);
                    document.body.removeChild(galleryOverlay);
                }
            });

            // 添加悬停效果
            imgContainer.addEventListener('mouseenter', () => {
                if (!imgContainer.style.borderColor || imgContainer.style.borderColor === 'transparent') {
                    imgContainer.style.borderColor = '#ccc';
                }
            });

            imgContainer.addEventListener('mouseleave', () => {
                if (!imgContainer.style.borderColor || imgContainer.style.borderColor === '#ccc') {
                    imgContainer.style.borderColor = 'transparent';
                }
            });
        });
    });

    // 多选模式下添加确认按钮
    if (isMultiple) {
        const confirmBtn = document.createElement('button');
        confirmBtn.textContent = '确认选择图片';
        confirmBtn.style.marginTop = '20px';
        confirmBtn.style.padding = '8px 16px';
        confirmBtn.style.backgroundColor = '#1890ff';
        confirmBtn.style.color = '#fff';
        confirmBtn.style.border = 'none';
        confirmBtn.style.borderRadius = '4px';
        confirmBtn.style.cursor = 'pointer';
        confirmBtn.style.fontSize = '14px';
        
        confirmBtn.addEventListener('click', () => {
            if (selectedImages.length > 0) {
                // 获取当前已有的图片
                let currentImages = this.getNestedValue(this.data, field.field) || [];
                if (!Array.isArray(currentImages)) {
                    currentImages = [currentImages];
                }
                
                // 合并新选中的图片
                const updatedImages = [...currentImages, ...selectedImages];
                
                // 检查是否是对象字段中的图片（通过容器上的同步函数）
                if (imageContainer && typeof imageContainer._syncImageData === 'function') {
                    console.log('检测到对象字段图片（多选），使用专用同步逻辑');
                    imageContainer._syncImageData(updatedImages);
                } else {
                    // 普通字段的处理
                    this.setNestedValue(this.data, field.field, updatedImages);
                }
                
                // 更新UI显示
                selectedImages.forEach(imgUrl => {
                    const newContainer = this.createImageItemContainer(imgUrl, field);
                    
                    // 紧急修复：强制显示图库选中的图片
                    newContainer.style.cssText = `
                        display: block !important;
                        visibility: visible !important;
                        opacity: 1 !important;
                        width: 100px !important;
                        height: 100px !important;
                        border: 1px solid #ddd !important;
                        border-radius: 4px !important;
                        position: relative !important;
                        margin-right: 10px !important;
                        margin-bottom: 10px !important;
                        background-color: #f9f9f9 !important;
                        z-index: 1000 !important;
                    `;
                    
                    const img = newContainer.querySelector('img');
                    if (img) {
                        img.style.cssText = `
                            display: block !important;
                            visibility: visible !important;
                            opacity: 1 !important;
                            width: 100% !important;
                            height: 100% !important;
                            object-fit: cover !important;
                        `;
                    }
                    
                    imageContainer.insertBefore(newContainer, previewContainer);
                    console.log('[图库选择] 图片容器已创建并强制显示:', imgUrl);
                });
                
                // 验证同步状态
                this.verifyMultiImageSync(field, imageContainer, '图库选择完成后');
                
                // 紧急修复：图库选择后也添加监控
                setTimeout(() => {
                    this.forceDisplayImageContainers(imageContainer, '图库选择后检查');
                    this.startEmergencyDisplayMonitor(imageContainer, field);
                }, 100);
            }
            document.body.removeChild(galleryOverlay);
        });
        galleryBox.appendChild(confirmBtn);
    }

    galleryBox.appendChild(imageGrid);
    galleryOverlay.appendChild(galleryBox);
    document.body.appendChild(galleryOverlay);

    // 点击遮罩关闭图库
    galleryOverlay.addEventListener('click', (e) => {
        if (e.target === galleryOverlay) {
            document.body.removeChild(galleryOverlay);
        }
    });
}

// 处理图片选择
handleImageSelect(imageUrl, field, previewContainer, clearBtn, hintText, plusIcon, errorEl, isMultiple, imageContainer) {
    // 更新数据
    if (isMultiple) {
        // 多选模式
        let currentImages = this.getNestedValue(this.data, field.field) || [];
        if (!Array.isArray(currentImages)) {
            currentImages = [currentImages];
        }
        currentImages.push(imageUrl);
        console.log('多选模式更新数据:', field.field, '新值:', currentImages);
        
        // 检查是否是对象字段中的图片（通过容器上的同步函数）
        if (imageContainer && typeof imageContainer._syncImageData === 'function') {
            console.log('检测到对象字段图片（多选），使用专用同步逻辑');
            imageContainer._syncImageData(currentImages);
        } else {
            // 普通字段的处理
            this.setNestedValue(this.data, field.field, currentImages);
        }
        
        // 创建新的图片容器
        const newContainer = this.createImageItemContainer(imageUrl, field);
        imageContainer.insertBefore(newContainer, previewContainer);
        
        // 验证同步状态
        this.verifyMultiImageSync(field, imageContainer, '单张图片选择后');
    } else {
        // 单选模式
        console.log('单选模式更新数据:', field.field, '新值:', imageUrl);
        console.log('更新前的数据状态:', JSON.stringify(this.data, null, 2));
        
        // 检查是否是对象字段中的图片（通过容器上的同步函数）
        if (imageContainer && typeof imageContainer._syncImageData === 'function') {
            console.log('检测到对象字段图片，使用专用同步逻辑');
            imageContainer._syncImageData(imageUrl);
        } else {
            // 普通字段的处理
            this.setNestedValue(this.data, field.field, imageUrl);
        }
        
        // 检查数据是否被正确更新
        const updatedValue = this.getNestedValue(this.data, field.field);
        console.log('验证更新后的值:', updatedValue);
        console.log('更新后的数据状态:', JSON.stringify(this.data, null, 2));

        // 移除之前的预览图片
        const existingImg = previewContainer.querySelector('.preview-image');
        if (existingImg) {
            previewContainer.removeChild(existingImg);
        }

        // 添加新图片到预览区域
        const previewImg = document.createElement('img');
        previewImg.src = imageUrl;
        previewImg.className = 'preview-image';
        previewImg.style.maxWidth = '100%';
        previewImg.style.maxHeight = '170px';
        previewImg.style.objectFit = 'contain';
        previewContainer.appendChild(previewImg);

        // 添加图片点击预览功能
        previewImg.style.cursor = 'zoom-in';
        previewImg.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡

            // 创建预览背景遮罩
            const previewOverlay = document.createElement('div');
            previewOverlay.style.position = 'fixed';
            previewOverlay.style.top = '0';
            previewOverlay.style.left = '0';
            previewOverlay.style.width = '100%';
            previewOverlay.style.height = '100%';
            previewOverlay.style.backgroundColor = 'rgba(0, 0, 0, 0.8)';
            previewOverlay.style.display = 'flex';
            previewOverlay.style.alignItems = 'center';
            previewOverlay.style.justifyContent = 'center';
            previewOverlay.style.zIndex = '99999999';
            previewOverlay.style.cursor = 'zoom-out';

            // 创建预览图片容器
            const previewBox = document.createElement('div');
            previewBox.style.maxWidth = '90%';
            previewBox.style.maxHeight = '90%';
            previewBox.style.display = 'flex';
            previewBox.style.alignItems = 'center';
            previewBox.style.justifyContent = 'center';

            // 创建预览图片
            const previewImage = document.createElement('img');
            previewImage.src = previewImg.src;
            previewImage.style.maxWidth = '100%';
            previewImage.style.maxHeight = '90vh';
            previewImage.style.objectFit = 'contain';

            // 添加到预览容器
            previewBox.appendChild(previewImage);
            previewOverlay.appendChild(previewBox);
            document.body.appendChild(previewOverlay);

            // 点击遮罩关闭预览
            previewOverlay.addEventListener('click', () => {
                document.body.removeChild(previewOverlay);
            });
        });

        // 显示清空按钮，隐藏提示文本和加号
        clearBtn.style.display = 'block';
        hintText.style.display = 'none';
        plusIcon.style.display = 'none';
    }
}

// 处理文件选择变化 - 全新优化的多文件上传函数
handleFileChange(files, field, previewContainer, loadingEl, clearBtn, hintText, plusIcon, errorEl, isMultiple, imageContainer) {
    console.log('[多文件上传] 开始处理文件选择', {
        fileCount: files.length,
        field: field.field,
        isMultiple: isMultiple
    });

    // 获取当前已有的图片 - 优先使用field_path
    const dataPath = field.field_path || field.field;
    let currentImages = isMultiple ? (this.getNestedValue(this.data, dataPath) || []) : '';
    if (isMultiple && !Array.isArray(currentImages)) {
        currentImages = [currentImages];
    }

    // 检查文件数量限制
    console.log('[文件数量限制检查]', {
        isMultiple: isMultiple,
        maxFiles: field.max_files,
        currentImages: currentImages,
        currentCount: Array.isArray(currentImages) ? currentImages.length : 0,
        newFileCount: files.length,
        field: field.field,
        fieldPath: field.field_path,
        dataPath: dataPath
    });
    
    if (isMultiple && field.max_files) {
        const currentCount = Array.isArray(currentImages) ? currentImages.length : 0;
        const newFileCount = files.length;
        const totalCount = currentCount + newFileCount;
        
        console.log('[文件数量限制详情]', {
            currentCount: currentCount,
            newFileCount: newFileCount,
            totalCount: totalCount,
            maxFiles: field.max_files,
            willExceed: totalCount > field.max_files
        });
        
        if (totalCount > field.max_files) {
            const allowedNewFiles = field.max_files - currentCount;
            console.log('[文件数量限制触发]', {
                allowedNewFiles: allowedNewFiles,
                willBlock: allowedNewFiles <= 0
            });
            
            if (allowedNewFiles <= 0) {
                this.showUploadError(errorEl, `最多只能上传 ${field.max_files} 张图片，当前已有 ${currentCount} 张`);
                return;
            } else {
                this.showUploadWarning(errorEl, `最多只能上传 ${field.max_files} 张图片，当前已有 ${currentCount} 张，只能再上传 ${allowedNewFiles} 张`);
                // 只取前 allowedNewFiles 个文件
                files = Array.from(files).slice(0, allowedNewFiles);
                console.log('[文件数量限制应用]', {
                    originalCount: newFileCount,
                    newCount: files.length,
                    removedCount: newFileCount - files.length
                });
            }
        }
    }

    // 验证文件 - 使用可能被数量限制修改后的files
    const validFiles = this.validateFiles(files);
    if (validFiles.invalid.length > 0) {
        this.showUploadError(errorEl, `有 ${validFiles.invalid.length} 个文件格式不支持，已跳过`);
    }
    
    if (validFiles.valid.length === 0) {
        this.showUploadError(errorEl, '没有有效的图片文件');
        return;
    }

    // 更新UI状态
    this.updateUploadUIState(loadingEl, hintText, plusIcon, errorEl, clearBtn, isMultiple, true);

    // 清除之前的预览图片（仅单选模式）
    if (!isMultiple) {
        const existingImg = previewContainer.querySelector('.preview-image');
        if (existingImg) {
            previewContainer.removeChild(existingImg);
        }
    }

    // 创建上传进度显示
    const progressContainer = this.createUploadProgressContainer(validFiles.valid.length);
    if (isMultiple) {
        imageContainer.insertBefore(progressContainer, previewContainer);
    }

    // 并行上传所有文件
    this.uploadMultipleFiles(validFiles.valid, field, currentImages, imageContainer, previewContainer, progressContainer, loadingEl, errorEl, isMultiple);
}

// 验证文件格式和大小
validateFiles(files) {
    const valid = [];
    const invalid = [];
    const maxSize = 10 * 1024 * 1024; // 10MB
    const allowedTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];

    Array.from(files).forEach(file => {
        if (!allowedTypes.includes(file.type.toLowerCase())) {
            invalid.push({ file, reason: '不支持的格式' });
        } else if (file.size > maxSize) {
            invalid.push({ file, reason: '文件过大' });
                        } else {
            valid.push(file);
        }
    });

    console.log('[文件验证] 有效文件:', valid.length, '无效文件:', invalid.length);
    return { valid, invalid };
}

// 更新上传UI状态
updateUploadUIState(loadingEl, hintText, plusIcon, errorEl, clearBtn, isMultiple, isUploading) {
    if (isUploading) {
        hintText.style.display = 'none';
        if (!isMultiple) {
            plusIcon.style.display = 'none';
        }
        loadingEl.style.display = 'flex';
        errorEl.style.display = 'none';
        clearBtn.style.display = 'none';
    } else {
        loadingEl.style.display = 'none';
        if (isMultiple) {
            plusIcon.style.display = 'flex';
        }
    }
}

// 创建上传进度显示容器
createUploadProgressContainer(totalFiles) {
    const progressContainer = document.createElement('div');
    progressContainer.className = 'upload-progress-container';
    progressContainer.style.cssText = `
        display: flex;
        flex-direction: column;
        gap: 8px;
        margin: 10px 0;
        padding: 10px;
        background: #f8f9fa;
        border: 1px solid #dee2e6;
        border-radius: 6px;
    `;

    const progressTitle = document.createElement('div');
    progressTitle.textContent = `正在上传 ${totalFiles} 个文件...`;
    progressTitle.style.cssText = `
        font-size: 14px;
        font-weight: 600;
        color: #495057;
        margin-bottom: 8px;
    `;

    const progressBar = document.createElement('div');
    progressBar.className = 'upload-progress-bar';
    progressBar.style.cssText = `
        width: 100%;
        height: 6px;
        background: #e9ecef;
        border-radius: 3px;
        overflow: hidden;
    `;

    const progressFill = document.createElement('div');
    progressFill.className = 'upload-progress-fill';
    progressFill.style.cssText = `
        height: 100%;
        background: linear-gradient(90deg, #007bff, #0056b3);
        width: 0%;
        transition: width 0.3s ease;
    `;

    progressBar.appendChild(progressFill);
    progressContainer.appendChild(progressTitle);
    progressContainer.appendChild(progressBar);

    return progressContainer;
}

// 并行上传多个文件
async uploadMultipleFiles(files, field, currentImages, imageContainer, previewContainer, progressContainer, loadingEl, errorEl, isMultiple) {
    const totalFiles = files.length;
    let completedFiles = 0;
    const successfulUrls = [];
    const failedFiles = [];

    // 更新进度条
    const updateProgress = () => {
        const progressFill = progressContainer.querySelector('.upload-progress-fill');
        const progressTitle = progressContainer.querySelector('div');
        const percentage = Math.round((completedFiles / totalFiles) * 100);
        
        if (progressFill) {
            progressFill.style.width = `${percentage}%`;
        }
        
        if (progressTitle) {
            progressTitle.textContent = `正在上传 ${completedFiles}/${totalFiles} 个文件...`;
        }
    };

    // 创建文件上传Promise
    const createUploadPromise = (file, index) => {
        return new Promise(async (resolve) => {
            try {
                console.log(`[文件上传] 开始上传文件 ${index + 1}/${totalFiles}:`, file.name);
                
                // 验证图片文件
                const isValidImage = await this.validateImageFile(file);
                if (!isValidImage) {
                    throw new Error('无效的图片文件');
                }

                // 上传文件
                const url = await uploadFile(file);
                if (!url) {
                    throw new Error('上传失败，未返回URL');
                }

                console.log(`[文件上传] 文件 ${index + 1} 上传成功:`, url);
                resolve({ success: true, url, file, index });
                
            } catch (error) {
                console.error(`[文件上传] 文件 ${index + 1} 上传失败:`, error);
                resolve({ success: false, error: error.message, file, index });
            }
        });
    };

    // 并行上传所有文件，但限制并发数量
    const maxConcurrent = 3; // 最多同时上传3个文件
    const uploadPromises = [];
    
    for (let i = 0; i < files.length; i += maxConcurrent) {
        const batch = files.slice(i, i + maxConcurrent);
        const batchPromises = batch.map((file, batchIndex) => 
            createUploadPromise(file, i + batchIndex)
        );
        
        // 等待当前批次完成
        const batchResults = await Promise.all(batchPromises);
        
        // 处理批次结果
        batchResults.forEach(result => {
            completedFiles++;
            updateProgress();
            
            if (result.success) {
                successfulUrls.push(result.url);
            } else {
                failedFiles.push({ file: result.file, error: result.error });
            }
        });
    }

    // 上传完成，处理结果
    this.handleUploadComplete(
        successfulUrls, 
        failedFiles, 
        field, 
        currentImages, 
        imageContainer, 
        previewContainer, 
        progressContainer, 
        loadingEl, 
        errorEl, 
        isMultiple
    );
}

// 验证图片文件
validateImageFile(file) {
    return new Promise((resolve) => {
        const reader = new FileReader();
        
        reader.onload = (event) => {
            const img = new Image();
            img.onload = () => resolve(true);
            img.onerror = () => resolve(false);
            img.src = event.target.result;
        };
        
        reader.onerror = () => resolve(false);
            reader.readAsDataURL(file);
        });
}

// 处理上传完成
handleUploadComplete(successfulUrls, failedFiles, field, currentImages, imageContainer, previewContainer, progressContainer, loadingEl, errorEl, isMultiple) {
    console.log('[上传完成] 成功:', successfulUrls.length, '失败:', failedFiles.length);

    // 移除进度容器
    if (progressContainer && progressContainer.parentNode) {
        progressContainer.parentNode.removeChild(progressContainer);
    }

    // 更新UI状态
    this.updateUploadUIState(loadingEl, null, null, errorEl, null, isMultiple, false);

    // 显示结果消息
    if (successfulUrls.length > 0 && failedFiles.length === 0) {
        this.showUploadSuccess(errorEl, `成功上传 ${successfulUrls.length} 个文件`);
    } else if (successfulUrls.length > 0 && failedFiles.length > 0) {
        this.showUploadWarning(errorEl, `成功上传 ${successfulUrls.length} 个文件，${failedFiles.length} 个失败`);
    } else {
        this.showUploadError(errorEl, '所有文件上传失败');
        return;
    }
        
        if (successfulUrls.length > 0) {
            // 更新数据
            if (isMultiple) {
            // 过滤重复图片
                const newImages = successfulUrls.filter(imgUrl => !currentImages.includes(imgUrl));
                const updatedImages = [...currentImages, ...newImages];
                
            // 同步数据
                if (imageContainer && typeof imageContainer._syncImageData === 'function') {
                console.log('[数据同步] 使用专用同步逻辑');
                    imageContainer._syncImageData(updatedImages);
                } else {
                    this.setNestedValue(this.data, field.field, updatedImages);
                }
                
            // 更新UI显示
            this.updateImageDisplay(newImages, field, imageContainer, previewContainer, isMultiple);
        } else {
            // 单选模式
            // 检查是否是对象字段中的图片（通过容器上的同步函数）
            if (imageContainer && typeof imageContainer._syncImageData === 'function') {
                console.log('[数据同步] 单选模式使用专用同步逻辑');
                imageContainer._syncImageData(successfulUrls[0]);
            } else {
                this.setNestedValue(this.data, field.field, successfulUrls[0]);
            }
            this.updateSingleImageDisplay(successfulUrls[0], previewContainer);
        }
    }
}

// 更新图片显示
updateImageDisplay(newImages, field, imageContainer, previewContainer, isMultiple) {
    console.log('[图片显示更新] 开始更新图片显示', {
        newImages: newImages,
        field: field.field,
        isMultiple: isMultiple,
        isObjectField: imageContainer && typeof imageContainer._syncImageData === 'function'
    });
    
                // 清除之前主预览容器中的图片（如果有）
                const existingMainImg = previewContainer.querySelector('.preview-image');
                if (existingMainImg) {
                    previewContainer.removeChild(existingMainImg);
                }
                
    // 创建新图片的容器
                newImages.forEach(imgUrl => {
                    const newContainer = this.createImageItemContainer(imgUrl, field);
                    
        // 优化样式设置 - 针对对象字段特殊处理
        if (imageContainer && typeof imageContainer._syncImageData === 'function') {
            // 对象字段中的图片容器样式
                    newContainer.style.cssText = `
                        display: block !important;
                        visibility: visible !important;
                        opacity: 1 !important;
                        width: 100px !important;
                        height: 100px !important;
                border: 2px solid #28a745 !important;
                border-radius: 6px !important;
                        position: relative !important;
                margin: 2px !important;
                background-color: #f8f9fa !important;
                        overflow: hidden !important;
                        z-index: 1000 !important;
                box-shadow: 0 2px 8px rgba(40, 167, 69, 0.2) !important;
                transition: all 0.3s ease !important;
                flex-shrink: 0 !important;
            `;
        } else {
            // 普通字段中的图片容器样式
            newContainer.style.cssText = `
                display: block !important;
                visibility: visible !important;
                opacity: 1 !important;
                width: 100px !important;
                height: 100px !important;
                border: 2px solid #28a745 !important;
                border-radius: 6px !important;
                position: relative !important;
                margin: 5px !important;
                background-color: #f8f9fa !important;
                overflow: hidden !important;
                z-index: 1000 !important;
                box-shadow: 0 2px 8px rgba(40, 167, 69, 0.2) !important;
                transition: all 0.3s ease !important;
            `;
        }
                    
                    // 强制显示内部图片
                    const img = newContainer.querySelector('img');
                    if (img) {
                        img.style.cssText = `
                            display: block !important;
                            visibility: visible !important;
                            opacity: 1 !important;
                            width: 100% !important;
                            height: 100% !important;
                            object-fit: cover !important;
                border-radius: 4px !important;
                        `;
                    }
                    
        // 将图片添加到容器前面，确保在虚线框外显示
                    imageContainer.insertBefore(newContainer, previewContainer);
                    
        console.log('[图片显示] 新图片容器已创建并显示:', imgUrl);
                });
                
    // 延迟验证显示状态
                setTimeout(() => {
        this.verifyImageDisplay(imageContainer, '上传完成后验证');
                }, 100);
}

// 更新单选图片显示
updateSingleImageDisplay(imgUrl, previewContainer) {
    const img = document.createElement('img');
    img.src = imgUrl;
    img.className = 'preview-image';
    img.style.cssText = `
        width: 100px !important;
        height: 100px !important;
        object-fit: cover !important;
        border-radius: 4px !important;
        border: 2px solid #007bff !important;
        display: block !important;
    `;
    
    previewContainer.appendChild(img);
    console.log('[单选显示] 图片已显示:', imgUrl);
}

// 验证图片显示状态
verifyImageDisplay(imageContainer, context) {
    const containers = imageContainer.querySelectorAll('.image-item-container');
    console.log(`[显示验证] ${context} - 容器数量:`, containers.length);
    
    containers.forEach((container, index) => {
        const style = window.getComputedStyle(container);
        const img = container.querySelector('img');
        
        if (style.display === 'none' || style.visibility === 'hidden' || style.opacity === '0') {
            console.warn(`[显示验证] 发现隐藏容器 ${index + 1}，强制显示`);
            container.style.display = 'block !important';
            container.style.visibility = 'visible !important';
            container.style.opacity = '1 !important';
        }
        
        if (img && (!img.src || img.src.trim() === '')) {
            console.warn(`[显示验证] 发现空图片容器 ${index + 1}`);
        }
    });
}

// 显示上传成功消息
showUploadSuccess(errorEl, message) {
    if (errorEl) {
        errorEl.textContent = message;
        errorEl.style.color = '#28a745';
        errorEl.style.display = 'block';
        
        // 3秒后自动隐藏
        setTimeout(() => {
            errorEl.style.display = 'none';
        }, 3000);
    }
    console.log('[上传成功]', message);
}

// 显示上传警告消息
showUploadWarning(errorEl, message) {
    if (errorEl) {
        errorEl.textContent = message;
        errorEl.style.color = '#ffc107';
        errorEl.style.display = 'block';
        
        // 5秒后自动隐藏
        setTimeout(() => {
            errorEl.style.display = 'none';
        }, 5000);
    }
    console.log('[上传警告]', message);
}

// 显示上传错误消息
showUploadError(errorEl, message) {
    if (errorEl) {
        errorEl.textContent = message;
        errorEl.style.color = '#dc3545';
            errorEl.style.display = 'block';
        
        // 错误消息不自动隐藏
        }
    console.error('[上传错误]', message);
}






   // 添加createFileUploadComponent非静态方法
    createFileUploadComponent(field, currentValue) {
        // 文件上传实现，样式与图片上传保持一致
        const fileContainer = document.createElement('div');
        fileContainer.className = 'file-container';
        fileContainer.style.display = 'flex';
        fileContainer.style.flexDirection = 'column';
        fileContainer.style.alignItems = 'center';
        fileContainer.style.justifyContent = 'center';
        fileContainer.style.width = '100px';
        fileContainer.style.height = '100px';
        fileContainer.style.border = '2px dashed #ccc';
        fileContainer.style.borderRadius = '4px';
        fileContainer.style.padding = '10px';
        fileContainer.style.boxSizing = 'border-box';
        fileContainer.style.cursor = 'pointer';
        fileContainer.style.position = 'relative'; // 添加相对定位，使删除按钮的绝对定位生效

        // 加号图标
        const filePlusIcon = document.createElement('div');
        filePlusIcon.style.width = '32px';
        filePlusIcon.style.height = '32px';
        filePlusIcon.style.borderRadius = '50%';
        filePlusIcon.style.display = 'flex';
        filePlusIcon.style.alignItems = 'center';
        filePlusIcon.style.justifyContent = 'center';
        filePlusIcon.style.color = '#999';
        filePlusIcon.style.fontSize = '45px';
        filePlusIcon.style.marginBottom = '10px';
        filePlusIcon.textContent = '+';

        // 提示文本
        const fileHintText = document.createElement('div');
        fileHintText.style.fontSize = '14px';
        fileHintText.style.color = '#666';
        fileHintText.style.textAlign = 'center';
        fileHintText.textContent = ''; 

        // 隐藏的文件输入
        const fileUploadInput = document.createElement('input');
        fileUploadInput.type = 'file';
        fileUploadInput.style.display = 'none';
        fileUploadInput.accept = field.accept || '*'; // 可通过field.accept指定接受的文件类型

        // 文件信息显示区域
        const fileInfo = document.createElement('div');
        fileInfo.className = 'file-info';
        fileInfo.style.width = '100%';
        fileInfo.style.display = 'none';
        fileInfo.style.flexDirection = 'column';
        fileInfo.style.alignItems = 'center';

        const fileName = document.createElement('div');
        fileName.style.fontSize = '14px';
        fileName.style.color = '#333';
        fileName.style.marginBottom = '5px';

        const fileSize = document.createElement('div');
        fileSize.style.fontSize = '12px';
        fileSize.style.color = '#666';

        // 加载状态
        const fileLoading = document.createElement('div');
        fileLoading.className = 'file-loading';
        fileLoading.style.display = 'none';
        fileLoading.style.fontSize = '14px';
        fileLoading.style.color = '#666';
        fileLoading.textContent = '上传中...';

        // 错误提示
        const fileError = document.createElement('div');
        fileError.className = 'file-error';
        fileError.style.display = 'none';
        fileError.style.fontSize = '14px';
        fileError.style.color = '#f44336';

        // 添加删除按钮
        const fileClearBtn = document.createElement('button');
        fileClearBtn.className = 'file-clear-btn';
        fileClearBtn.style.width = '20px';
        fileClearBtn.style.height = '20px';
        fileClearBtn.style.position = 'absolute';
        fileClearBtn.style.top = '5px';
        fileClearBtn.style.right = '5px';
        fileClearBtn.style.backgroundColor = 'transparent';
        fileClearBtn.style.backgroundImage = 'url(./assets/images/index/del.png)';
        fileClearBtn.style.backgroundSize = 'contain';
        fileClearBtn.style.backgroundRepeat = 'no-repeat';
        fileClearBtn.style.backgroundPosition = 'center';
        fileClearBtn.style.border = 'none';
        fileClearBtn.style.padding = '0';
        fileClearBtn.style.margin = '0';
        fileClearBtn.style.cursor = 'pointer';
        fileClearBtn.style.display = 'none'; // 初始隐藏
        fileClearBtn.title = '删除文件';

        // 组装容器
        fileInfo.appendChild(fileName);
        fileInfo.appendChild(fileSize);
        fileContainer.appendChild(filePlusIcon);
        fileContainer.appendChild(fileHintText);
        fileContainer.appendChild(fileUploadInput);
        fileContainer.appendChild(fileInfo);
        fileContainer.appendChild(fileLoading);
        fileContainer.appendChild(fileError);
        fileContainer.appendChild(fileClearBtn); // 添加删除按钮到容器

        // 删除按钮点击事件
        fileClearBtn.addEventListener('click', (e) => {
            e.stopPropagation(); // 阻止事件冒泡，避免触发文件选择

            // 清除文件数据
            this.setNestedValue(this.data, field.field, '');

            // 重置文件输入控件
            fileUploadInput.value = '';

            // 隐藏删除按钮和文件信息
            fileClearBtn.style.display = 'none';
            fileInfo.style.display = 'none';

            // 显示提示文本和加号图标
            filePlusIcon.style.display = 'flex';
            fileHintText.style.display = 'block';

            // 隐藏错误提示
            fileError.style.display = 'none';
        });

        // 点击容器触发文件选择
        fileContainer.addEventListener('click', () => {
            fileUploadInput.click();
        });

        // 拖拽支持
        fileContainer.addEventListener('dragover', (e) => {
            e.preventDefault();
            fileContainer.style.borderColor = '#3b82f6';
            fileContainer.style.backgroundColor = 'rgba(59, 130, 246, 0.05)';
        });

        fileContainer.addEventListener('dragleave', () => {
            fileContainer.style.borderColor = '#ccc';
            fileContainer.style.backgroundColor = 'transparent';
        });

        fileContainer.addEventListener('drop', (e) => {
            e.preventDefault();
            fileContainer.style.borderColor = '#ccc';
            fileContainer.style.backgroundColor = 'transparent';

            if (e.dataTransfer.files.length) {
                handleFileSelection(e.dataTransfer.files[0]);
            }
        });

        // 文件选择处理
        fileUploadInput.addEventListener('change', (e) => {
            if (e.target.files.length) {
                handleFileSelection(e.target.files[0]);
            }
        });

        // 处理选中的文件（改为箭头函数）
        const handleFileSelection = (file) => {
            // 显示加载状态
            filePlusIcon.style.display = 'none';
            fileHintText.style.display = 'none';
            fileInfo.style.display = 'none';
            fileError.style.display = 'none';
            fileLoading.style.display = 'block';
            fileClearBtn.style.display = 'none'; // 隐藏删除按钮

            // 调用uploadFile函数上传文件
            uploadFile(file).then(url => {
                // 隐藏加载状态
                fileLoading.style.display = 'none';

                if (url) {
                    // 显示文件信息
                    fileName.textContent = file.name;
                    fileSize.textContent = formatFileSize(file.size);
                    fileInfo.style.display = 'flex';
                    fileClearBtn.style.display = 'block'; // 显示删除按钮

                    // 更新数据为返回的URL
                    this.setNestedValue(this.data, field.field, url);
                } else {
                    // 上传失败，显示错误信息
                    fileError.style.display = 'block';
                    fileError.textContent = '文件上传失败，请重试';
                    filePlusIcon.style.display = 'flex';
                    fileHintText.style.display = 'block';
                }
            }).catch(error => {
                // 上传出错，显示错误信息
                fileLoading.style.display = 'none';
                fileError.style.display = 'block';
                fileError.textContent = '文件上传出错，请重试';
                filePlusIcon.style.display = 'flex';
                fileHintText.style.display = 'block';
            });
        };

        // 格式化文件大小
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        return fileContainer;
    }







    // 静态初始化方法
    static init(options) {
        const { container, initialData, fieldCategories, expandedCategories = {}, formTitle, apiUrl } = options;

        // 创建表单相关元素
        FormGenerator.createFormElements(container, formTitle);
        // 保存原始数据深拷贝用于比较
        const originalDataCopy = JSON.parse(JSON.stringify(initialData));

        // 添加美化后的无变化弹窗样式
        FormGenerator.addPopupStyles();
        //表单数据提交接口
        FormGenerator.apiUrl = apiUrl;
        //

        // 初始化表单生成器
        const formGenerator = new FormGenerator({
            container,
            initialData,
            fieldCategories,
            expandedCategories // 传递展开状态参数
        });
        formGenerator.renderForm();

        // 绑定保存按钮事件
        FormGenerator.bindSaveButton(formGenerator, originalDataCopy);
        // 初始化快速到底部按钮
        FormGenerator.initScrollToBottomButton();
        // 添加这一行，返回创建的实例
        return formGenerator;
    }
    static apiUrl = 'https://default-api-endpoint.com';
    // 新增：创建表单元素
    static createFormElements(containerSelector, formTitle) {
        // 获取容器元素
        const containerEl = typeof containerSelector === 'string'
            ? document.querySelector(containerSelector)
            : containerSelector;

        if (!containerEl) return;

        // 创建form-container元素
        const formContainer = document.createElement('div');
        formContainer.className = 'form-container';

        // 创建标题
        const title = document.createElement('h1');
        title.textContent = formTitle;
        formContainer.appendChild(title);

        // 保存原始的form-content元素
        const formContent = containerEl.cloneNode(false);
        containerEl.parentNode.replaceChild(formContainer, containerEl);

        // 将form-content添加到form-container
        formContainer.appendChild(formContent);

        // 创建保存按钮
        const saveBtn = document.createElement('button');
        saveBtn.id = 'save-btn';
        saveBtn.textContent = '保存配置';
        saveBtn.style.float = 'right';  // 右对齐
        saveBtn.style.marginTop = '-15px';  // 向上移动10像素
        saveBtn.style.marginRight = '50px';  // 向左移动70像素，避免与
        formContainer.appendChild(saveBtn);

        // 创建保存状态显示
        const saveStatus = document.createElement('div');
        saveStatus.id = 'save-status';
        saveStatus.className = 'save-status';
        formContainer.appendChild(saveStatus);

        // 创建快速到底部按钮
        const scrollBtn = document.createElement('button');
        scrollBtn.id = 'scroll-to-bottom';
        scrollBtn.title = '快速到底部';
        scrollBtn.textContent = '▼';
        document.body.appendChild(scrollBtn);
    }

    // 添加弹窗样式
    static addPopupStyles() {
        const style = document.createElement('style');
        style.textContent = `
            /* 弹窗遮罩层 */
            .popup-overlay {
                position: fixed;
                top: 0;
                left: 0;
                right: 0;
                bottom: 0;
                background: rgba(0, 0, 0, 0.5);
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 99999999;
                backdrop-filter: blur(2px);
                animation: fadeIn 0.3s ease;
            }

            /* 弹窗容器 */
            .no-changes-popup {
                background-color: #fff;
                border-radius: 12px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
                width: 320px;
                overflow: hidden;
                animation: scaleIn 0.3s ease;
            }

            /* 弹窗头部 */
            .popup-header {
                background-color: #f5f7fa;
                padding: 16px;
                border-bottom: 1px solid #e8e8e8;
                display: flex;
                align-items: center;
                justify-content: center;
            }

            /* 弹窗图标 */
            .popup-icon {
                width: 24px;
                height: 24px;
                border-radius: 50%;
                background-color: #e6f7ff;
                color: #1890ff;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 14px;
                font-weight: bold;
                margin-right: 12px;
            }

            /* 弹窗标题 */
            .popup-title {
                font-size: 16px;
                font-weight: 500;
                color: #1f2937;
                margin: 0;
                text-align: center;
            }

            /* 弹窗内容 */
            .popup-content {
                padding: 20px;
                font-size: 14px;
                color: #4b5563;
                line-height: 1.5;
                text-align: center;
            }

            /* 弹窗底部 */
            .popup-footer {
                padding: 12px 20px;
                border-top: 1px solid #e8e8e8;
                display: flex;
                justify-content: center;
            }

            /* 确认按钮 */
            .popup-confirm-btn {
                padding: 8px 20px;
                background-color: #1890ff;
                color: white;
                border: none;
                border-radius: 6px;
                font-size: 14px;
                cursor: pointer;
                transition: all 0.2s;
            }

            .popup-confirm-btn:hover {
                background-color: #096dd9;
                box-shadow: 0 2px 8px rgba(24, 144, 255, 0.3);
            }

            /* 动画效果 */
            @keyframes fadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }

            @keyframes scaleIn {
                from { transform: scale(0.95); opacity: 0; }
                to { transform: scale(1); opacity: 1; }
            }
        `;
        document.head.appendChild(style);
    }

    // 绑定保存按钮事件
    static bindSaveButton(formGenerator, originalDataCopy) {
        const saveBtn = document.getElementById('save-btn');
        saveBtn.addEventListener('click', function () {
            const updatedData = formGenerator.getUpdatedData();
            
            // 添加：在检测变更前创建一个不包含组合字段的副本
            const filteredUpdatedData = JSON.parse(JSON.stringify(updatedData));
            for (const key in filteredUpdatedData) {
                if (Object.prototype.hasOwnProperty.call(filteredUpdatedData, key)) {
                    // 同时过滤顶级字段"组合"和以"组合."开头的字段
                    if (key === '组合' || key.startsWith('组合.')) {
                        delete filteredUpdatedData[key];
                    }
                }
            }
            
            if (FormGenerator.deepEqual(originalDataCopy, filteredUpdatedData)) {
                FormGenerator.createNoChangesPopup();
            } else {
                // 使用过滤后的数据分析变更
                const changes = FormGenerator.getChanges(originalDataCopy, filteredUpdatedData);
                FormGenerator.createChangesPopup(changes, function () {
                    // 调用API提交数据，并添加回调函数
                    FormGenerator.submitDataToApi(
                        updatedData, // 注意：这里仍然使用原始的updatedData，因为submitDataToApi中会再次过滤
                        originalDataCopy,
                        // 成功回调函数
                        function(result) {
                            console.log('保存成功，触发uploadSuccess事件:', result);
                            // 触发uploadSuccess事件
                            const uploadSuccessEvent = new CustomEvent('uploadSuccess', {
                                detail: {
                                    excel_url: result.excel_url || '',
                                    pdf_url: result.pdf_url || '',
                                    result: result
                                }
                            });
                            document.dispatchEvent(uploadSuccessEvent);
                        },
                        // 错误回调函数
                        function(error) {
                            console.error('保存失败，触发uploadError事件:', error);
                            // 触发uploadError事件
                            const uploadErrorEvent = new CustomEvent('uploadError', {
                                detail: {
                                    error: error
                                }
                            });
                            document.dispatchEvent(uploadErrorEvent);
                        }
                    );
                });
            }
        });
    }
    // 提交数据到API
    static submitDataToApi = async function (data, originalDataCopy, successCallback, errorCallback) {
        try {
            // 确保apiUrl已定义
            const apiUrl = FormGenerator.apiUrl;
            if (!apiUrl) {
                throw new Error('API URL未定义');
            }
            
            // 在提交前检查并转换支持语言格式
            if (data && data.软件配置V2 && data.软件配置V2.语言 && Array.isArray(data.软件配置V2.语言.支持语言)) {
                data.软件配置V2.语言.支持语言 = data.软件配置V2.语言.支持语言.join('、');
            }
            
            // 在删除组合字段之前，先确保组合字段中的数据正确映射到目标位置
            if (data && data.组合) {
                console.log('[数据映射] 开始处理组合字段数据映射:', data.组合);
                
                // 处理尺寸屏幕形状组合
                if (data.组合['尺寸屏幕形状组合']) {
                    const sizeScreenData = data.组合['尺寸屏幕形状组合'];
                    console.log('[数据映射] 从组合字段获取尺寸和屏幕形状数据:', sizeScreenData);
                    
                    // 确保软件配置V3存在
                    if (!data.软件配置V3) {
                        data.软件配置V3 = {};
                    }
                    
                    // 映射尺寸数据
                    if (sizeScreenData.尺寸 !== undefined) {
                        data.软件配置V3.尺寸 = sizeScreenData.尺寸;
                        console.log('[数据映射] 已映射尺寸数据:', sizeScreenData.尺寸);
                    }
                    
                    // 映射屏幕形状数据
                    if (sizeScreenData.屏幕形状 !== undefined) {
                        data.软件配置V3.屏幕形状 = sizeScreenData.屏幕形状;
                        console.log('[数据映射] 已映射屏幕形状数据:', sizeScreenData.屏幕形状);
                    }
                }
                
                // 处理蓝牙音频语言组合
                if (data.组合['蓝牙音频语言组合']) {
                    const bluetoothAudioData = data.组合['蓝牙音频语言组合'];
                    console.log('[数据映射] 从组合字段获取蓝牙音频数据:', bluetoothAudioData);
                    
                    // 确保软件配置V1存在
                    if (!data.软件配置V1) {
                        data.软件配置V1 = {};
                    }
                    
                    // 映射蓝牙名数据
                    if (bluetoothAudioData.蓝牙名 !== undefined) {
                        data.软件配置V1.蓝牙名 = bluetoothAudioData.蓝牙名;
                        console.log('[数据映射] 已映射蓝牙名数据:', bluetoothAudioData.蓝牙名);
                    }
                    
                    // 映射音频名数据
                    if (bluetoothAudioData.音频名 !== undefined) {
                        data.软件配置V1.音频名 = bluetoothAudioData.音频名;
                        console.log('[数据映射] 已映射音频名数据:', bluetoothAudioData.音频名);
                    }
                }
                
                // 处理基础版本表盘组合
                if (data.组合['基础版本表盘组合']) {
                    const baseVersionData = data.组合['基础版本表盘组合'];
                    console.log('[数据映射] 从组合字段获取基础版本表盘数据:', baseVersionData);
                    
                    // 映射基础版本数据
                    if (baseVersionData.基础版本 !== undefined) {
                        data.基础版本 = baseVersionData.基础版本;
                        console.log('[数据映射] 已映射基础版本数据:', baseVersionData.基础版本);
                    }
                    
                    // 确保软件配置V5存在
                    if (!data.软件配置V5) {
                        data.软件配置V5 = {};
                    }
                    
                    // 映射表盘数据
                    if (baseVersionData.表盘 !== undefined) {
                        data.软件配置V5.表盘 = baseVersionData.表盘;
                        console.log('[数据映射] 已映射表盘数据:', baseVersionData.表盘);
                    }
                }
                
                console.log('[数据映射] 组合字段数据映射完成');
            }
            
            // 为总成配置中的每一个总成都添加尺寸和屏幕形状数据
            if (data && data.软件配置V3) {

                
                
                // 遍历所有总成配置
                Object.keys(data.软件配置V3).forEach(key => {
                    if (key.startsWith('总成') && typeof data.软件配置V3[key] === 'object') {
                        const assembly = data.软件配置V3[key];
                        
                        // 添加尺寸和屏幕形状数据
                        assembly.尺寸 = currentScreenShape;
                        assembly.屏幕形状 = currentScreenShape;
                        
                        console.log(`[总成配置] 已为${key}添加尺寸和屏幕形状:`, {
                            尺寸: assembly.尺寸,
                            屏幕形状: assembly.屏幕形状
                        });
                    }
                });
                
            }
            
            // 修改：删除所有以"组合."开头的字段
            for (const key in data) {
                if (Object.prototype.hasOwnProperty.call(data, key)) {
                    if (key === '组合' || key.startsWith('组合.')) {
                        delete data[key];
                    }
                }
            }
            
            //提交的时候增加参数客户名称，项目代号，提交时间
            data.客户名称 = customerName;
            data.项目代号 = projectName;
            data.提交时间 = FormGenerator.getFormattedTime();
            const response = await fetch(apiUrl, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ data: data })
            });

            if (!response.ok) {
                const errorMsg = `HTTP 错误! 状态码: ${response.status}`;
                console.error(errorMsg);
                if (errorCallback) {
                    errorCallback(errorMsg);
                }
                return;
            }

            // 获取响应文本，然后尝试解析为JSON
            let resultText;
            try {
                resultText = await response.text();
                //console.log('响应文本:', resultText); // 调试信息
                if (!resultText.trim()) {
                    // 空响应处理
                    if (successCallback) {
                        successCallback({});
                    }
                    return {};
                }
                // 尝试解析JSON
                const result = JSON.parse(resultText);

                // 更新原始数据拷贝
                if (originalDataCopy) {
                    try {
                        Object.assign(originalDataCopy, JSON.parse(JSON.stringify(data)));
                    } catch (assignError) {
                        console.error('数据更新错误:', assignError.message);
                    }
                } else {
                    console.warn('originalDataCopy未定义，无法更新数据');
                }

                if (successCallback) {
                    successCallback(result);
                }
                return result;
            } catch (jsonError) {
                const errorMsg = `响应解析错误: ${jsonError.message}\n响应文本: ${resultText}`;
                console.error(errorMsg);
                if (errorCallback) {
                    errorCallback(errorMsg);
                }
                return;
            }
        } catch (error) {
            const errorMsg = `API 调用失败: ${error.message}`;
            console.error(errorMsg);
            if (errorCallback) {
                errorCallback(errorMsg);
            }
            return;
        }
    };
    static getFormattedTime() {
        const date = new Date();
        // 获取各时间部分并补零
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        
        // 拼接成目标格式
        return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    }

    // 深比较函数
    static deepEqual(obj1, obj2, excludeFields = []) {
        // 处理null情况
        if (obj1 === null && obj2 === null) return true;
        if (obj1 === null || obj2 === null) return false;

        // 处理基本类型比较
        if (typeof obj1 !== 'object' || typeof obj2 !== 'object') {
            return obj1 === obj2;
        }

        // 处理数组
        if (Array.isArray(obj1) && Array.isArray(obj2)) {
            if (obj1.length !== obj2.length) return false;
            for (let i = 0; i < obj1.length; i++) {
                if (!FormGenerator.deepEqual(obj1[i], obj2[i], excludeFields)) return false;
            }
            return true;
        }

        // 处理对象，排除指定字段
        const keys1 = Object.keys(obj1).filter(key => !excludeFields.includes(key));
        const keys2 = Object.keys(obj2).filter(key => !excludeFields.includes(key));

        if (keys1.length !== keys2.length) return false;

        for (const key of keys1) {
            if (!keys2.includes(key) || !FormGenerator.deepEqual(obj1[key], obj2[key], excludeFields)) {
                return false;
            }
        }

        return true;
    }

    // 变更检测函数
    static getChanges(original, current, path = '') {
        const changes = [];
        if (FormGenerator.deepEqual(original, current)) return changes;

        // 定义需要按父节点聚合的路径
        const aggregatePaths = [
            '软件配置V2.语言.支持语言',
            '软件配置J1.TP快捷4方向',
            '软件配置J1.主菜单风格',
            '软件配置J1.按键.Power按键',
            '软件配置J1.按键.编码器按键',
            '软件配置J1.按键.侧键',
            '软件配置J1.按键.运动侧键',
            '软件配置J1.按键.快捷功能键',
            '软件配置J2',
            '系统功能J3',
            '软件配置V3.总成1',
            '软件配置V3.总成2',
            '软件配置V3.总成3',
            '软件配置V3.总成4',
            '软件配置V3.总成5',
            '软件配置V3.总成6',
            '软件配置V3.总成7',
            '软件配置V3.总成8',
            '软件配置V3.总成9',
            '软件配置V3.总成10',
            '软件配置V3.总成11',
            '软件配置V3.总成12',
        ];

        if (typeof original === 'object' && typeof current === 'object' && original && current) {
            [...new Set([...Object.keys(original), ...Object.keys(current)])].forEach(k => {
                const newPath = path ? `${path}.${k}` : k;

                // 修改：跳过所有以"组合."开头的字段的检测
                if (k === '组合' || k.startsWith('组合.') || newPath === '组合' || newPath.startsWith('组合.')) {
                    return; // 跳过处理
                }
                
                // 检查是否是需要聚合的父节点
                if (aggregatePaths.includes(newPath)) {
                    // 对于这些父节点，直接添加变更记录而不递归
                    if (!FormGenerator.deepEqual(original[k], current[k])) {
                        changes.push({ path: newPath, original: original[k], current: current[k], status: '修改' });
                    }
                    return; // 跳过递归处理
                }

                if (!original.hasOwnProperty(k)) {
                    changes.push({ path: newPath, original: undefined, current: current[k], status: '增加' });
                } else if (!current.hasOwnProperty(k)) {
                    // 直接标记为删除，不进行位置变化判断
                    changes.push({ path: newPath, original: original[k], current: undefined, status: '删除' });
                } else if (!FormGenerator.deepEqual(original[k], current[k])) {
                    if (typeof original[k] === 'object' && typeof current[k] === 'object' && original[k] && current[k])
                        changes.push(...FormGenerator.getChanges(original[k], current[k], newPath));
                    else
                        changes.push({ path: newPath, original: original[k], current: current[k], status: '修改' });
                }
            });
        } else {
            // 对于非对象值，如果路径以"组合."开头，也跳过
            if (path !== '组合' && !path.startsWith('组合.')) {
                changes.push({ path, original, current, status: original === undefined ? '增加' : current === undefined ? '删除' : '修改' });
            }
        }
        return changes;
    }
    

    // 格式化函数
    static formatValue(value) {
        if (value === undefined || value === null) {
            return "无";
        }
        if (typeof value === 'object' && !Array.isArray(value)) {
            // 对于对象，返回格式化的JSON字符串
            return JSON.stringify(value, null, 2);
        }
        if (Array.isArray(value)) {
            // 对于数组，返回格式化的JSON字符串
            return JSON.stringify(value, null, 2);
        }
        return value.toString();
    }

    // 创建无变更弹窗
    static createNoChangesPopup() {
        // 如果没有layui，直接执行
        const overlay = document.createElement('div');
        overlay.className = 'popup-overlay';

        const popup = document.createElement('div');
        popup.className = 'no-changes-popup';
        popup.innerHTML = `
        <div class="popup-header">
            <div class="popup-icon">i</div>
            <h3 class="popup-title">保存失败</h3>
        </div>
        <div class="popup-content">
            没有检测到任务修改！
        </div>
        <div class="popup-footer">
            <button class="popup-confirm-btn">关闭</button>
        </div>
    `;
        overlay.appendChild(popup);
        document.body.appendChild(overlay);

        popup.querySelector('.popup-confirm-btn').addEventListener('click', () => {
            document.body.removeChild(overlay);
        });

        overlay.addEventListener('click', (e) => {
            if (e.target === overlay) {
                document.body.removeChild(overlay);
            }
        });

    }

    // 创建变更确认弹窗
    static createChangesPopup(changes, confirmCallback) {
        // 分类变更数据
        const additions = changes.filter(change => change.status === '增加');
        const modifications = changes.filter(change => change.status === '修改');
        const deletions = changes.filter(change => change.status === '删除');

        const overlay = document.createElement('div');
        overlay.className = 'popup-overlay';
        overlay.style.cssText = 'position:fixed;top:0;left:0;width:100%;height:100%;background:rgba(0,0,0,0.5);z-index:99999998;';

        const popup = document.createElement('div');
        popup.className = 'changes-popup';
        popup.style.cssText = 'position:fixed;top:50%;left:50%;transform:translate(-50%,-50%);background:white;padding:15px;border-radius:8px;box-shadow:0 0 10px rgba(0,0,0,0.3);z-index:99999999;max-width:90%;width:100%;max-height:80vh;display:flex;flex-direction:column;overflow:hidden;';

        // 创建tab按钮
        const tabContainer = document.createElement('div');
        tabContainer.style.cssText = 'display:flex;border-bottom:1px solid #ddd;margin-bottom:10px;';

        // 按照用户要求调整tab顺序和背景色
        const addTabBtn = document.createElement('button');
        addTabBtn.textContent = `增加 (${additions.length})`;
        addTabBtn.style.cssText = 'flex:1;padding:8px;background:#2196f3;border:none;cursor:pointer;color:white;';
        addTabBtn.dataset.tab = 'add';

        const modifyTabBtn = document.createElement('button');
        modifyTabBtn.textContent = `修改 (${modifications.length})`;
        modifyTabBtn.style.cssText = 'flex:1;padding:8px;background:white;border:none;cursor:pointer;color:black;';
        modifyTabBtn.dataset.tab = 'modify';

        const deleteTabBtn = document.createElement('button');
        deleteTabBtn.textContent = `删除 (${deletions.length})`;
        deleteTabBtn.style.cssText = 'flex:1;padding:8px;background:#f44336;border:none;cursor:pointer;color:white;';
        deleteTabBtn.dataset.tab = 'delete';

        // 按照用户要求的顺序添加tab按钮
        tabContainer.appendChild(addTabBtn);
        tabContainer.appendChild(modifyTabBtn);
        tabContainer.appendChild(deleteTabBtn);

        // 设置默认选中第一个有数据的tab
        let defaultTab = 'add';
        if (additions.length > 0) defaultTab = 'add';
        else if (modifications.length > 0) defaultTab = 'modify';
        else if (deletions.length > 0) defaultTab = 'delete';

        // 创建表格容器
        const tableContainer = document.createElement('div');
        tableContainer.className = 'table-container';
        tableContainer.style.cssText = 'overflow-y:scroll !important;max-height:calc(80vh - 200px);margin:10px 0;flex-grow:1;padding-right:5px;-webkit-overflow-scrolling:touch;';

    

    
     

    
    // 创建表格
    const createTable = (data) => {
    if (data.length === 0) {
        const emptyMsg = document.createElement('div');
        emptyMsg.textContent = '暂无数据';
        emptyMsg.style.cssText = 'text-align:center;padding:20px;color:#666;';
        return emptyMsg;
    }

    const table = document.createElement('table');
    table.style.cssText = 'width:100%;border-collapse:collapse;table-layout:fixed;';

    const thead = document.createElement('thead');
    thead.innerHTML = `
    <tr style='background:#f0f0f0'>
        <th style='padding:6px;text-align:left;border:1px solid #ddd;white-space:nowrap;'>配置路径</th>
        <th style='padding:6px;text-align:left;border:1px solid #ddd;'>原始值</th>
        <th style='padding:6px;text-align:left;border:1px solid #ddd;'>修改值</th>
    </tr>`;

    const tbody = document.createElement('tbody');
    tbody.innerHTML = data.map(change => {
        // 特殊处理支持语言数组的显示
        let originalValue = FormGenerator.formatValue(change.original);
        let currentValue = FormGenerator.formatValue(change.current);

        // 如果是支持语言字段且原始值和当前值都是数组，则计算差异
        if (change.path === '软件配置V2.语言.支持语言' && Array.isArray(change.original) && Array.isArray(change.current)) {
            // 计算新增的语言
            const addedLanguages = change.current.filter(lang => !change.original.includes(lang));
            // 计算删除的语言
            const removedLanguages = change.original.filter(lang => !change.current.includes(lang));
            // 计算未变化的语言
            const unchangedLanguages = change.original.filter(lang => change.current.includes(lang));
            
            // 使用卡片式布局展示语言信息
            originalValue = `
                <div style="font-weight: bold; margin-bottom: 5px;">原有语言:</div>
                <div style="display: flex; flex-wrap: wrap; gap: 5px;">${
                    change.original.map(lang => 
                        `<span style="background-color: #f5f5f5; padding: 4px 8px; border-radius: 12px; border: 1px solid #e0e0e0; font-size: 12px;">${lang}</span>`
                    ).join('')
                }</div>`;
            
            // 最终值展示 - 只显示变更详情，不显示最终语言的子项
            let changeDetails = '';
            if (addedLanguages.length > 0 || removedLanguages.length > 0) {
                changeDetails = `
                        <div style="font-weight: bold; margin-bottom: 5px;">变更:</div>
                        <div style="display: flex; flex-wrap: wrap; gap: 5px; margin-bottom: 5px;">${
                            addedLanguages.map(lang => 
                                `<span style="background-color: #e8f5e9; color: #2563eb; padding: 3px 6px; border-radius: 10px; font-size: 11px;">+ ${lang}</span>`
                            ).join('')
                        }${
                            removedLanguages.map(lang => 
                                `<span style="background-color: #ffebee; color: #c62828; padding: 3px 6px; border-radius: 10px; font-size: 11px;">- ${lang}</span>`
                            ).join('')
                        }</div>
                    `;
            }
            
            currentValue = changeDetails;
        } 
        // 处理对象类型的字段，显示新增、删除、修改的key，但不显示最终对象的子项
        else if (typeof change.original === 'object' && change.original !== null && 
                 typeof change.current === 'object' && change.current !== null &&
                 !Array.isArray(change.original) && !Array.isArray(change.current)) {
            
            // 获取所有唯一的key
            const allKeys = new Set([
                ...Object.keys(change.original),
                ...Object.keys(change.current)
            ]);
            
            // 分类key
            const addedKeys = [];
            const deletedKeys = [];
            const modifiedKeys = [];
            const unchangedKeys = [];
            
            allKeys.forEach(key => {
                const inOriginal = key in change.original;
                const inCurrent = key in change.current;
                
                if (inOriginal && inCurrent) {
                    // 检查值是否相同
                    if (JSON.stringify(change.original[key]) !== JSON.stringify(change.current[key])) {
                        modifiedKeys.push(key);
                    } else {
                        unchangedKeys.push(key);
                    }
                } else if (inOriginal && !inCurrent) {
                    deletedKeys.push(key);
                } else if (!inOriginal && inCurrent) {
                    addedKeys.push(key);
                }
            });
            
            // 显示原始值
            originalValue = `
                <div style="font-weight: bold; margin-bottom: 5px;">原始对象:</div>
                <div style="display: flex; flex-direction: column; gap: 3px;">${
                    Object.keys(change.original).map(key => 
                        `<div style="display: flex; align-items: center; padding: 2px 0;">
                            <span style="background-color: #f5f5f5; padding: 2px 6px; border-radius: 8px; border: 1px solid #e0e0e0; font-size: 11px; margin-right: 5px;">${key}</span>
                            <span style="font-size: 11px; color: #666;">: ${JSON.stringify(change.original[key])}</span>
                        </div>`
                    ).join('')
                }</div>`;
            
            // 最终值只显示变更详情，不显示最终对象的子项
            let changeDetails = '';
            if (addedKeys.length > 0 || deletedKeys.length > 0 || modifiedKeys.length > 0) {
                changeDetails = `
                        <div style="font-weight: bold; margin-bottom: 5px;">变更:</div>
                        <div style="display: flex; flex-direction: column; gap: 3px;">${
                            addedKeys.map(key => 
                                `<div style="display: flex; align-items: center; padding: 2px 0;">
                                    <span style="background-color: #e8f5e9; color: #2563eb; padding: 2px 6px; border-radius: 8px; font-size: 11px; margin-right: 5px;">+ ${key}</span>
                                    <span style="font-size: 11px; color: #666;">: ${JSON.stringify(change.current[key])}</span>
                                </div>`
                            ).join('')
                        }${
                            deletedKeys.map(key => 
                                `<div style="display: flex; align-items: center; padding: 2px 0;">
                                    <span style="background-color: #ffebee; color: #c62828; padding: 2px 6px; border-radius: 8px; font-size: 11px; margin-right: 5px;">- ${key}</span>
                                    <span style="font-size: 11px; color: #666;">: ${JSON.stringify(change.original[key])}</span>
                                </div>`
                            ).join('')
                        }${
                            modifiedKeys.map(key => 
                                `<div style="display: flex; padding: 2px 0;">
                                    <div style="display: flex; align-items: center; margin-right: 10px;">
                                        <span style="background-color: #fff3e0; color: #ef6c00; padding: 2px 6px; border-radius: 8px; font-size: 11px; margin-right: 5px;">~ ${key}</span>
                                    </div>
                                    <div style="display: flex; flex-direction: column;">
                                        <div style="display: flex; align-items: center;">
                                            <span style="font-size: 10px; color: #999; margin-right: 5px;">原:</span>
                                            <span style="font-size: 11px; color: #666;">${JSON.stringify(change.original[key])}</span>
                                        </div>
                                        <div style="display: flex; align-items: center;">
                                            <span style="font-size: 10px; color: #999; margin-right: 5px;">新:</span>
                                            <span style="font-size: 11px; color: #666;">${JSON.stringify(change.current[key])}</span>
                                        </div>
                                    </div>
                                </div>`
                            ).join('')
                        }</div>
                    `;
            }
            
            currentValue = changeDetails;
        }
        // 处理数组类型的字段，显示新增、删除的元素
        else if (Array.isArray(change.original) && Array.isArray(change.current)) {
            // 计算新增的元素
            const addedItems = change.current.filter(item => !change.original.includes(item));
            // 计算删除的元素
            const removedItems = change.original.filter(item => !change.current.includes(item));
            // 计算未变化的元素
            const unchangedItems = change.original.filter(item => change.current.includes(item));
            
            // 使用卡片式布局展示原始数组元素
            originalValue = `
                <div style="font-weight: bold; margin-bottom: 5px;">原始数组:</div>
                <div style="display: flex; flex-wrap: wrap; gap: 5px;">${
                    change.original.map(item => 
                        `<span style="background-color: #f5f5f5; padding: 4px 8px; border-radius: 12px; border: 1px solid #e0e0e0; font-size: 12px;">${JSON.stringify(item)}</span>`
                    ).join('')
                }</div>`;
            
            // 最终值只显示变更详情，不显示最终数组的子项
            let changeDetails = '';
            if (addedItems.length > 0 || removedItems.length > 0) {
                changeDetails = `
                        <div style="font-weight: bold; margin-bottom: 5px;">变更:</div>
                        <div style="display: flex; flex-wrap: wrap; gap: 5px; margin-bottom: 5px;">${
                            addedItems.map(item => 
                                `<span style="background-color: #e8f5e9; color: #2563eb; padding: 3px 6px; border-radius: 10px; font-size: 11px;">+ ${JSON.stringify(item)}</span>`
                            ).join('')
                        }${
                            removedItems.map(item => 
                                `<span style="background-color: #ffebee; color: #c62828; padding: 3px 6px; border-radius: 10px; font-size: 11px;">- ${JSON.stringify(item)}</span>`
                            ).join('')
                        }</div>
                    `;
            }
            
            currentValue = changeDetails;
        } else {
            // 非数组字段或非支持语言字段的处理保持不变
            if (change.path === '软件配置V2.语言.支持语言' && Array.isArray(change.original)) {
                originalValue = change.original.join('、');
            }
            if (change.path === '软件配置V2.语言.支持语言' && Array.isArray(change.current)) {
                currentValue = change.current.join('、');
            }
        }

        return `
        <tr>
            <td style='padding:6px;border:1px solid #ddd;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;'>${change.path}</td>
            <td style='padding:6px;border:1px solid #ddd;white-space:pre-wrap;word-break:break-all;vertical-align:top;'>${originalValue}</td>
            <td style='padding:6px;border:1px solid #ddd;white-space:pre-wrap;word-break:break-all;vertical-align:top;'>${currentValue}</td>
        </tr>`;
    }).join('');

    table.appendChild(thead);
    table.appendChild(tbody);
    return table;
};



         // 显示指定tab的内容
    const showTab = (tabType) => {
        // 更新按钮样式
        [addTabBtn, modifyTabBtn, deleteTabBtn].forEach(btn => {
            if (btn.dataset.tab === tabType) {
                // 选中状态的样式
                if (tabType === 'add') {
                    btn.style.background = '#2196f3';
                    btn.style.color = 'white';
                    btn.style.fontWeight = 'bold';
                } else if (tabType === 'modify') {
                    btn.style.background = 'white';
                    btn.style.color = 'black';
                    btn.style.fontWeight = 'bold';
                } else if (tabType === 'delete') {
                    btn.style.background = '#f44336';
                    btn.style.color = 'white';
                    btn.style.fontWeight = 'bold';
                }
            } else {
                // 未选中状态的样式
                btn.style.background = '#f0f0f0';
                btn.style.color = 'black';
                btn.style.fontWeight = 'normal';
            }
        });

        // 清空并添加新内容
        tableContainer.innerHTML = '';
        switch (tabType) {
            case 'add':
                tableContainer.appendChild(createTable(additions));
                break;
            case 'modify':
                tableContainer.appendChild(createTable(modifications));
                break;
            case 'delete':
                tableContainer.appendChild(createTable(deletions));
                break;
        }
    };

    // 绑定tab按钮事件
    addTabBtn.addEventListener('click', () => showTab('add'));
    modifyTabBtn.addEventListener('click', () => showTab('modify'));
    deleteTabBtn.addEventListener('click', () => showTab('delete'));

    // 默认显示第一个有数据的tab
    showTab(defaultTab);

    // 修改这里：移除标题和描述文字框
    popup.innerHTML = '';
    popup.appendChild(tabContainer);
    popup.appendChild(tableContainer);

    const buttonContainer = document.createElement('div');
    buttonContainer.style.cssText = 'text-align:center;margin-top:15px;display:flex;justify-content:center;gap:10px;';
    buttonContainer.innerHTML = `
    <button id='confirm-save' style='padding:6px 12px;background:#3b82f6;color:white;border:none;border-radius:4px;flex:1;max-width:120px;'>是</button>
    <button id='cancel-save' style='padding:6px 12px;background:#f44336;color:white;border:none;border-radius:4px;flex:1;max-width:120px;'>否</button>`;
    popup.appendChild(buttonContainer);

    // 添加响应式样式
    const style = document.createElement('style');
    style.textContent = `
    @media (max-width: 600px) {
        .table-container {
            overflow-x: auto;
            -webkit-overflow-scrolling: touch;
        }
        table {
            min-width: 500px;
        }
    }
`;
    popup.appendChild(style);

    overlay.appendChild(popup);
    document.body.appendChild(overlay);

    popup.querySelector('#cancel-save').addEventListener('click', () => {
        document.body.removeChild(overlay);
    });

    popup.querySelector('#confirm-save').addEventListener('click', () => {
        document.body.removeChild(overlay);
        if (typeof confirmCallback === 'function') {
            confirmCallback();
        } else {
            console.error('确认回调函数未定义');
        }
    });
    }

    // 显示保存状态
    static showStatus(message, type) {
        const statusEl = document.getElementById('save-status');
        statusEl.textContent = message;
        statusEl.className = 'save-status ' + type;
        statusEl.style.display = 'block';
        setTimeout(() => {
            statusEl.style.display = 'none';
        }, 3000);
    }

    // 初始化快速到底部按钮
    static initScrollToBottomButton() {
        //console.log('开始初始化滚动到底部按钮');

        // 检查layui是否已加载
        if (typeof layui === 'undefined') {
            console.error('layui未加载，无法初始化滚动到底部按钮');
            return;
        }

        // 适配layui 1.x版本
        let $ = null;
        if (typeof layui.$ !== 'undefined') {
            $ = layui.$;
            console.log('使用layui.$');
        } else if (typeof layui.jquery !== 'undefined') {
            $ = layui.jquery;
            console.log('使用layui.jquery');
        } else if (typeof window.$ !== 'undefined') {
            $ = window.$;
            //console.log('使用全局$');
        } else {
            console.error('未找到jQuery，将使用原生JavaScript');
            // 如果没有jQuery，使用原生JavaScript实现
            this.initScrollToBottomButtonNative();
            return;
        }

        // 查找layer弹窗容器，如果存在则使用弹窗容器，否则使用document.body
        let parentContainer = document.body;
        const layerPopup = document.querySelector('.layui-layer-content');
        if (layerPopup) {
            parentContainer = layerPopup;
            //console.log('检测到layer弹窗，将使用弹窗作为父容器');
        } else {
            console.log('未检测到layer弹窗，将使用document.body作为父容器');
        }

        // 检查并获取或创建滚动到底部按钮
        let scrollToBottomBtn = document.getElementById('scroll-to-bottom');

        // 如果按钮不存在，则创建一个
        if (!scrollToBottomBtn) {
            console.warn('未找到滚动到底部按钮元素，将创建一个新的');
            scrollToBottomBtn = document.createElement('button');
            scrollToBottomBtn.id = 'scroll-to-bottom';

            // 根据父容器类型设置定位
            if (layerPopup) {
                // 在layer弹窗中使用绝对定位
                scrollToBottomBtn.style.position = 'absolute';
            } else {
                // 在普通页面中使用固定定位
                scrollToBottomBtn.style.position = 'fixed';
            }

            // 按钮样式设置
            scrollToBottomBtn.style.bottom = '20px';
            scrollToBottomBtn.style.right = '20px';
            scrollToBottomBtn.style.zIndex = '9999'; // 提高层级确保可见
            scrollToBottomBtn.style.backgroundColor = '#4CAF50'; // 绿色背景
            scrollToBottomBtn.style.color = 'white'; // 白色文字
            scrollToBottomBtn.style.border = 'none'; // 无边框
            scrollToBottomBtn.style.borderRadius = '50%'; // 圆形按钮
            scrollToBottomBtn.style.width = '50px'; // 宽度
            scrollToBottomBtn.style.height = '50px'; // 高度
            scrollToBottomBtn.style.display = 'flex'; // 使用flex布局
            scrollToBottomBtn.style.alignItems = 'center'; // 垂直居中
            scrollToBottomBtn.style.justifyContent = 'center'; // 水平居中
            scrollToBottomBtn.style.cursor = 'pointer'; // 鼠标悬停样式
            scrollToBottomBtn.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)'; // 添加阴影
            scrollToBottomBtn.style.transition = 'all 0.3s ease'; // 过渡效果
            scrollToBottomBtn.textContent = '↓'; // 简化文本为箭头
            scrollToBottomBtn.style.transform = 'scale(0)'; // 初始缩放为0

            // 添加到父容器
            parentContainer.appendChild(scrollToBottomBtn);
            //console.log('已创建并添加滚动到底部按钮');
        } else {
            //console.log('找到滚动到底部按钮，开始设置');
            // 重置按钮样式
            scrollToBottomBtn.style.display = 'flex';
            scrollToBottomBtn.style.transform = 'scale(0)';
        }

        // 初始隐藏按钮
        setTimeout(() => {
            scrollToBottomBtn.style.display = 'none';
        }, 10);

        // 定义滚动处理函数
        function handleScroll() {
            // 使用适配的$方法获取滚动距离
            let scrollTop = 0;
            if (layerPopup) {
                // 在layer弹窗中
                scrollTop = $(layerPopup).scrollTop();
                //console.log('handleScroll函数被调用(layer弹窗)，滚动距离:', scrollTop);
            } else {
                // 在普通页面中
                scrollTop = $(window).scrollTop();
                //console.log('handleScroll函数被调用(window)，滚动距离:', scrollTop);
            }

            if (scrollTop > 300) {
                //console.log('滚动距离大于300px，显示按钮');
                scrollToBottomBtn.style.display = 'flex';
                // 强制重排
                void scrollToBottomBtn.offsetWidth;
                // 显示动画
                scrollToBottomBtn.style.transform = 'scale(1)';
            } else {
                //console.log('滚动距离小于等于300px，隐藏按钮');
                // 隐藏动画
                scrollToBottomBtn.style.transform = 'scale(0)';
                // 动画完成后隐藏
                setTimeout(() => {
                    scrollToBottomBtn.style.display = 'none';
                }, 300);
            }
        }

        // 初始检查是否需要显示按钮
        handleScroll();

        // 监听窗口大小变化
        $(window).on('resize', handleScroll);

        // 监听滚动事件，控制按钮显示/隐藏
        try {
            if (layerPopup) {
                // 在layer弹窗中
                $(layerPopup).on('scroll', handleScroll);
            } else {
                // 在普通页面中
                $(window).on('scroll', handleScroll);
            }
        } catch (error) {
            //console.error('添加滚动事件监听器失败:', error);
        }

        // 点击按钮滚动到底部
        try {
            $(scrollToBottomBtn).on('click', () => {
                if (layerPopup) {
                    // 在layer弹窗中，使用动画滚动到顶部
                    $(layerPopup).animate({
                        scrollTop: layerPopup.scrollHeight
                    }, 500);
                    //console.log('点击滚动到底部按钮，已滚动到弹窗底部');
                } else {
                    // 在普通页面中，使用动画滚动到顶部
                    $('html, body').animate({
                        scrollTop: $(document).height()
                    }, 500);
                    //console.log('点击滚动到底部按钮，已滚动到页面底部');
                }
            });
            //console.log('点击事件监听器已添加');
        } catch (error) {
            //console.error('添加点击事件监听器失败:', error);
        }
    }

    // 原生JavaScript实现的滚动到底部按钮
    static initScrollToBottomButtonNative() {
        //console.log('开始使用原生JavaScript初始化滚动到底部按钮');

        // 查找layer弹窗容器，如果存在则使用弹窗容器，否则使用document.body
        let parentContainer = document.body;
        const layerPopup = document.querySelector('.layui-layer-content');
        if (layerPopup) {
            parentContainer = layerPopup;
            //console.log('检测到layer弹窗，将使用弹窗作为父容器');
        } else {
            //console.log('未检测到layer弹窗，将使用document.body作为父容器');
        }

        // 检查并获取或创建滚动到底部按钮
        let scrollToBottomBtn = document.getElementById('scroll-to-bottom');

        // 如果按钮不存在，则创建一个
        if (!scrollToBottomBtn) {
            console.warn('未找到滚动到底部按钮元素，将创建一个新的');
            scrollToBottomBtn = document.createElement('button');
            scrollToBottomBtn.id = 'scroll-to-bottom';

            // 根据父容器类型设置定位
            if (layerPopup) {
                // 在layer弹窗中使用绝对定位
                scrollToBottomBtn.style.position = 'absolute';
            } else {
                // 在普通页面中使用固定定位
                scrollToBottomBtn.style.position = 'fixed';
            }

            // 按钮样式设置
            scrollToBottomBtn.style.bottom = '20px';
            scrollToBottomBtn.style.right = '20px';
            scrollToBottomBtn.style.zIndex = '9999'; // 提高层级确保可见
            scrollToBottomBtn.style.backgroundColor = '#4CAF50'; // 绿色背景
            scrollToBottomBtn.style.color = 'white'; // 白色文字
            scrollToBottomBtn.style.border = 'none'; // 无边框
            scrollToBottomBtn.style.borderRadius = '50%'; // 圆形按钮
            scrollToBottomBtn.style.width = '50px'; // 宽度
            scrollToBottomBtn.style.height = '50px'; // 高度
            scrollToBottomBtn.style.display = 'flex'; // 使用flex布局
            scrollToBottomBtn.style.alignItems = 'center'; // 垂直居中
            scrollToBottomBtn.style.justifyContent = 'center'; // 水平居中
            scrollToBottomBtn.style.cursor = 'pointer'; // 鼠标悬停样式
            scrollToBottomBtn.style.boxShadow = '0 2px 10px rgba(0,0,0,0.2)'; // 添加阴影
            scrollToBottomBtn.style.transition = 'all 0.3s ease'; // 过渡效果
            scrollToBottomBtn.textContent = '↓'; // 简化文本为箭头
            scrollToBottomBtn.style.transform = 'scale(0)'; // 初始缩放为0

            // 添加到父容器
            parentContainer.appendChild(scrollToBottomBtn);
            //console.log('已创建并添加滚动到底部按钮');
        } else {
            //console.log('找到滚动到底部按钮，开始设置');
            // 重置按钮样式
            scrollToBottomBtn.style.display = 'flex';
            scrollToBottomBtn.style.transform = 'scale(0)';
        }

        // 初始隐藏按钮
        setTimeout(() => {
            scrollToBottomBtn.style.display = 'none';
        }, 10);

        // 定义滚动处理函数
        function handleScroll() {
            // 使用原生JavaScript获取滚动距离
            let scrollTop = 0;
            if (layerPopup) {
                // 在layer弹窗中
                scrollTop = layerPopup.scrollTop || 0;
                //console.log('handleScroll函数被调用(layer弹窗)，滚动距离:', scrollTop);
            } else {
                // 在普通页面中
                scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0;
                // console.log('handleScroll函数被调用(window)，滚动距离:', scrollTop);
            }

            if (scrollTop > 300) {
                //console.log('滚动距离大于300px，显示按钮');
                scrollToBottomBtn.style.display = 'flex';
                // 强制重排
                void scrollToBottomBtn.offsetWidth;
                // 显示动画
                scrollToBottomBtn.style.transform = 'scale(1)';
            } else {
                //console.log('滚动距离小于等于300px，隐藏按钮');
                // 隐藏动画
                scrollToBottomBtn.style.transform = 'scale(0)';
                // 动画完成后隐藏
                setTimeout(() => {
                    scrollToBottomBtn.style.display = 'none';
                }, 300);
            }
        }

        // 初始检查是否需要显示按钮
        handleScroll();

        // 监听窗口大小变化
        window.addEventListener('resize', handleScroll);

        // 监听滚动事件，控制按钮显示/隐藏
        try {
            if (layerPopup) {
                // 在layer弹窗中
                layerPopup.addEventListener('scroll', handleScroll);
            } else {
                // 在普通页面中
                window.addEventListener('scroll', handleScroll);
                document.addEventListener('scroll', handleScroll);
            }
        } catch (error) {
            console.error('添加滚动事件监听器失败:', error);
        }

        // 点击按钮滚动到底部
        try {
            scrollToBottomBtn.addEventListener('click', () => {
                if (layerPopup) {
                    // 在layer弹窗中，使用原生JavaScript滚动到顶部
                    const scrollToBottom = () => {
                        const currentScroll = layerPopup.scrollTop;
                        const targetScroll = layerPopup.scrollHeight;

                        if (currentScroll < targetScroll) {
                            // 计算滚动步长
                            const scrollStep = Math.max(1, Math.floor((targetScroll - currentScroll) / 20));
                            layerPopup.scrollTop = currentScroll + scrollStep;

                            // 继续滚动
                            requestAnimationFrame(scrollToBottom);
                        }
                    };

                    // 开始滚动
                    requestAnimationFrame(scrollToBottom);
                    //console.log('点击滚动到底部按钮，已滚动到弹窗底部');
                } else {
                    // 在普通页面中，使用原生JavaScript滚动到顶部
                    const scrollToBottom = () => {
                        const currentScroll = window.pageYOffset || document.documentElement.scrollTop;
                        const targetScroll = document.body.scrollHeight;

                        if (currentScroll < targetScroll) {
                            // 计算滚动步长
                            const scrollStep = Math.max(1, Math.floor((targetScroll - currentScroll) / 20));
                            window.scrollTo(0, currentScroll + scrollStep);

                            // 继续滚动
                            requestAnimationFrame(scrollToBottom);
                        }
                    };

                    // 开始滚动
                    requestAnimationFrame(scrollToBottom);
                    //console.log('点击滚动到底部按钮，已滚动到页面底部');
                }
            });
            //console.log('点击事件监听器已添加');
        } catch (error) {
            console.error('添加点击事件监听器失败:', error);
        }
    }
}

// 添加全局调试函数
window.debugImageContainers = () => {
    const containers = document.querySelectorAll('.image-item-container');
    console.log('=== 图片容器调试信息 ===');
    console.log('容器总数:', containers.length);
    containers.forEach((container, index) => {
        const style = window.getComputedStyle(container);
        const img = container.querySelector('img');
        console.log(`容器${index + 1}:`, {
            display: style.display,
            visibility: style.visibility,
            opacity: style.opacity,
            src: img?.src,
            width: style.width,
            height: style.height
        });
    });
    console.log('=== 调试信息结束 ===');
};

// 添加数据调试函数
window.debugImageData = (fieldPath) => {
    if (!fieldPath) {
        fieldPath = '软件配置J1.主菜单风格.参考附图';
    }
    console.log('=== 图片数据调试信息 ===');
    console.log('字段路径:', fieldPath);
    
    if (window.formGeneratorInstance) {
        const rawData = window.formGeneratorInstance.getNestedValue(window.formGeneratorInstance.data, fieldPath);
        console.log('原始数据:', rawData);
        console.log('数据类型:', typeof rawData);
        console.log('是否为数组:', Array.isArray(rawData));
        
        if (Array.isArray(rawData)) {
            console.log('数组长度:', rawData.length);
            console.log('数组内容:', rawData);
            
            const validData = rawData.filter(img => {
                const isValid = img && img.trim() !== '' && (img.startsWith('http') || img.startsWith('/') || img.includes('\\') || img.includes('/'));
                return isValid;
            });
            console.log('有效数据长度:', validData.length);
            console.log('有效数据内容:', validData);
        }
    } else {
        console.error('表单实例未找到');
    }
    console.log('=== 数据调试信息结束 ===');
};
